[][src]Attribute Macro inject::inject

#[inject]

Generate functionality for a function/constructor to be injectable

#inject accepts two positions: in a "free" function, or a struct impl method that returns Self.

Examples

When in struct impl position, a new associated method inject is generated, in which the get! macro is invoked for each argument.

use ::inject::*;

#[derive(Debug, PartialEq)]
struct A(String);

impl A {
    #[inject]
    fn new(string: String) -> Self {
        Self(string)
    }
}

let container = Container::new();
assert_eq!(A::new("".into()), A::inject(&container).unwrap())

When in free function position, a set of macro_rules macros are generated (and hidden), which enables injection and kwarg-style resolution of the function arguments.

use ::inject::*;

#[inject]
fn injectable(a: usize, b: usize) -> usize { a + b }

// A container with a value provider for "usize"
let container = container![
    |container: &Container| Ok(2usize),
];

// Call the function, letting injection resolve the values
let result = call!(&container, injectable).unwrap();
assert_eq!(result, 4);

// Use kwargs to provide a value for one of the args of the function
// By using macros generated by the #[inject] attribute.
let result = call!(&container, injectable, kwargs = { b: 12 }).unwrap();
assert_eq!(result, 14);