[][src]Macro inject::get

get!() { /* proc-macro */ }

Resolve a dependency from a container

get!(..) accepts 2-3 arguments.

  1. The first argument can be any expression, and should return a reference to a Container instance.
  2. The second argument should be a type which we want to resolve, optionally prepended by an '&' to indicate that we want a reference.
  3. Lastly, the create: (true|false) key-value can be supplied to indicate that we only want to use a Provider for the type, NOT the associated inject method.

Example

use ::inject::*;

// Derive default for brevity, see #[inject] for more intricate usages.
#[derive(Default)]
struct Foo;

let container = Container::new();

// 1. Attempt to resolve a reference
let result = get!(&container, &Foo);

// Fails because no reference-provider is installed into "container".
assert!(result.is_err());

// 2. Attempt to resolve a value
let result = get!(&container, Foo);

// Succeeds because the type could be resolved with injection using Foo::inject(&container).
assert!(result.is_ok());

// 3. Attempt to resolve a value, but ONLY using a Provider
let result = get!(&container, Foo, create: false);

// Fails because no value-provider is installed into "container".
assert!(result.is_err());

The create: (true|false) key-value only holds meaning for value types. New references cannot be created by the macro, as their corresponding instance is dropped on return.