[−][src]Macro inject::call
call!() { /* proc-macro */ }
Call a function with dependency resolution for its arguments
`call!(..) accepts 2-3 arguments.
- The first argument can be any expression, and should return a
reference to a
Container
instance. - The second argument should be the name of a function that has been annotated using the #inject attribute.
- Optionally, a sequence of keyword-value-arguments (kwargs) can be supplied on the form
kwargs = {arg1: expr1, arg2: expr2}
, for a method with arguments
Examples
use ::inject::*; // A function that can be called with call!(..) #[inject] fn foo(a: isize) -> isize { a + 1 } // An empty container. let container = container![]; // call "foo", argument(s) resolved using injection. // This time, it will be resolved to 0 (default). let result = call!(&container, foo).unwrap(); assert_eq!(result, 1); // call "foo", this time using the provided kwarg "a = 2" let result = call!(&container, foo, kwargs = { a: 2 }).unwrap(); assert_eq!(result, 3);
Kwargs are parsed recursively and can be supplied in any order. They take precedence over any installed provider for the invoking of the function.
use ::inject::*; // A struct which is allowed to be constructed // with a provided "isize" type. struct Injectable(isize); impl Injectable { #[inject] fn new(a: isize) -> Self { Self(a) } } #[inject] fn callable(injectable: Injectable) { println!("{} + {} = {}", injectable.0, 2, injectable.0 + 2); } let mut container = container![]; // prints 0 + 2 = 2 call!(&container, callable); container.install(|container: &Container| Ok(Injectable::new(3))); // prints 3 + 2 = 5 call!(&container, callable); // prints 1 + 2 = 3 call!(&container, callable, kwargs = { injectable: Injectable::new(1) });
Under the hood, if an arg is not provided a corresponding kwarg, the
get!
macro is used to evaluate the argument.