#injection #thruster #quick #jab

thruster-jab

Quick and simple dependency injection

1 unstable release

0.1.0 Oct 22, 2021

#12 in #thruster

Download history 26/week @ 2023-12-17 15/week @ 2023-12-24 26/week @ 2023-12-31 67/week @ 2024-01-07 30/week @ 2024-01-14 14/week @ 2024-01-21 32/week @ 2024-01-28 11/week @ 2024-02-04 32/week @ 2024-02-11 23/week @ 2024-02-18 114/week @ 2024-02-25 22/week @ 2024-03-03 35/week @ 2024-03-10 26/week @ 2024-03-17 4/week @ 2024-03-24 34/week @ 2024-03-31

102 downloads per month
Used in thruster

MIT license

12KB
131 lines

Thruster Jab

Because this is a dependency injection library, and shots are injected, and shots are called jabs in the UK.

What is this?

Thruster Jab is a dependency injection library for your service injection needs. It works using dynamic dispatch via Box<dyn Any>. If you're looking to make something that will need mocks in order to test (say, an API that makes external calls, or a service that is very expensive) then Jab might be helpful to you.

Example

Although built for thruster, Jab can be used independently. A simple example would be:

struct A(i32);

trait C {}

impl C for A {}

let mut jab = JabDI::default();

let a = A(0);

provide!(jab, dyn C, a);
let something = fetch!(jab, dyn C); // This is the original a that we passed in, now as a C trait.

A slightly longer, but more "copy pasta" example (taken from our tests because I'm lazy) would be:

// Just making two structs that impl two traits
#[derive(Debug, PartialEq)]
struct A(i32);

#[derive(Debug, PartialEq)]
struct B(i32);

trait C {
    fn valc(&self) -> i32;
}
trait D {
    fn vald(&self) -> i32;
}

impl C for A {
    fn valc(&self) -> i32 {
        self.0
    }
}

impl D for B {
    fn vald(&self) -> i32 {
        self.0
    }
}

// This is the good part
let mut jab = JabDI::default();

let a = A(0);
let b = B(1);

provide!(jab, dyn C, a);
provide!(jab, dyn D, b);

assert_eq!(
    0,
    fetch!(jab, dyn C).valc(),
    "it should correctly find struct A for trait C"
);

assert_eq!(
    1,
    fetch!(jab, dyn D).vald(),
    "it should correctly find struct B for trait D"
);

For use with actual tests, check out our hello_world.rs example.

No runtime deps