More Dependency Injection Crate

Crates.io MIT licensed

This library contains all of the fundamental abstractions for dependency injection (DI). A trait or struct can be used as the injected type.

Features

This crate provides the following features:

Service Lifetimes

A service can have the following lifetimes:

Examples

Consider the following traits and structures:

```rust use di::ServiceRef;

trait Foo { fn speak(&self) -> String; }

trait Bar { fn speak(&self) -> String; }

[derive(Default)]

struct FooImpl { }

impl Foo for FooImpl { fn speak(&self) -> String { String::from("foo") } }

struct BarImpl { foo: ServiceRef }

impl BarImpl { fn new(foo: ServiceRef) -> Self { Self { foo } } }

impl Bar for BarImpl { fn speak(&self) -> String { let mut text = self.foo.speak(); text.push_str(" bar"); text } } ```

Service Registration and Resolution

```rust fn main() { let mut services = ServiceCollection::new();

services.add(
    singleton::<dyn Foo, FooImpl>()
    .from(|_| Rc::new(FooImpl::default())));
services.add(
    transient::<dyn Bar, BarImpl>()
    .from(|sp| Rc::new(BarImpl::new(sp.get_required::<dyn Foo>()))));

let provider = services.build_provider().unwrap();
let bar = provider.get_required::<dyn Bar>();
let text = bar.speak();

assert_eq!(text, "foo bar")

} ```

Figure 1: Basic usage

Note: singleton and transient are utility functions provided by the builder feature.

In the preceding example, ServiceCollection::add is used to add ServiceDescriptor instances. The framework also provides ServiceCollection::try_add, which only registers the service if there isn't already an implementation registered.

In the following example, the call to try_add has no effect because the service has already been registered:

```rust let mut services = ServiceCollection::new();

services.add(transient::().from(|| Rc::new(Foo2::default()))); services.tryadd(transient::().from(|_| Rc::new(FooImpl::default()))); ```

Scope Scenarios

There scenarios where a service needs to be scoped; for example, for the lifetime of a HTTP request. A service definitely shouldn't live for the life of the application (e.g. singleton), but it also shouldn't be created each time it's requested within the request (e.g. transient). A scoped service lives for the lifetime of the container it was created from.

```rust let provider = ServiceCollection::new() .add( scoped::() .from(|| Rc::new(FooImpl::default()))) .add( transient::() .from(|sp| Rc::new(BarImpl::new(sp.getrequired::())))) .build_provider() .unwrap();

{ // create a scope where Bar is shared let scope = provider.createscope(); let bar1 = provider.getrequired::(); let bar2 = provider.get_required::();

assert!(Rc::ptr_eq(&bar1, &bar2));

}

{ // create a new scope where Bar is shared and different from before let scope = provider.createscope(); let bar1 = provider.getrequired::(); let bar2 = provider.get_required::();

assert!(Rc::ptr_eq(&bar1, &bar2));

} ```

Figure 2: Using scoped services

Note: scoped and transient are utility functions provided by the builder feature.

Validation

The consumers of a ServiceProvider expect that is correctly configured and ready for use. There are edge cases, however, which could lead to runtime failures.

Intrinsic validation has been added to ensure this cannot happen. The build_provider() function will return Result<ServiceProvider, ValidationError>, which will either contain a valid ServiceProvider or a ValidationError that will detail all of the errors. From that point forward, the ServiceProvider will be considered semantically correct and safe to use. The same validation process can also be invoked imperatively on-demand by using the di::validate function.

The ServiceDescriptorBuilder cannot automatically determine the dependencies your service may require. This means that validation is an explicit, opt-in capability. If you do not configure any dependencies for a ServiceDescriptor, then no validation will occur.

```rust fn main() { let mut services = ServiceCollection::new();

services.add(
    singleton::<dyn Foo, FooImpl>()
    .from(|_| Rc::new(FooImpl::default())));
services.add(
    transient::<dyn Bar, BarImpl>()
    .depends_on(exactly_one::<dyn Foo>())
    .from(|sp| Rc::new(BarImpl::new(sp.get_required::<dyn Foo>()))));

match services.build_provider() {
    Ok(provider) => {
        let bar = provider.get_required::<dyn Bar>();
        assert_eq!(&bar.speak(), "foo bar");
    },
    Err(error) => {
        println!("The service configuration is invalid.\n{}", &error.to_string());
    }
}

} ``` Figure 3: Validating service configuration

Note: singleton, transient, and exactly_one are utility functions provided by the builder feature.

Inject Feature

The Injectable trait can be implemented so that structures can be injected as a single, supported trait or as themselves.

```rust use di::*; use std::rc::Rc;

impl Injectable for FooImpl { fn inject(lifetime: ServiceLifetime) -> ServiceDescriptor { ServiceDescriptorBuilder::::new(lifetime, Type::of::()) .from(|_| Rc::new(FooImpl::default())) } }

impl Injectable for BarImpl { fn inject(lifetime: ServiceLifetime) -> ServiceDescriptor { ServiceDescriptorBuilder::::new(lifetime, Type::of::()) .from(|sp| Rc::new(BarImpl::new(sp.get_required::()))) } } ```

Figure 4: Implementing Injectable

While implementing Injectable might be necessary or desired in a handful of scenarios, it is mostly tedious ceremony. If the injection call site were known, then it would be possible to provide the implementation automatically. This is exactly what the #[injectable] attribute provides.

Instead of implementing Injectable by hand, the implementation simply applies a decorator:

```rust use di::injectable; use std::rc::Rc;

[injectable(Bar)]

impl BarImpl { fn new(foo: Rc) -> Self { Self { foo: foo } } } ```

Figure 5: Automatically implementing Injectable

Injection Rules

Notice that the attribute is decorated on the impl of the struct as opposed to a trait implementation. This is because this is the location where the associated function that will be used to construct the struct is expected to be found. This allows the attribute to inspect the injection call site to build the proper implementation. The attribute contains the trait to be satisfied. If this process where reversed, it would require a lookahead or lookbehind to search for the implementation.

By default, the attribute will search for an associated function named new. The function does not need to be pub. This is a simple convention that works for most cases; however, if you want to use a different name, the intended function must be decorated with the #[inject] attribute. This attribute simply indicates which function to use. If new and a decorated function are defined, the decorated function will take precedence. If multiple functions have #[inject] applied, an error will occur.

Call site arguments must conform to the return values from:

This means that the only allowed arguments are:

ServiceRef<T> is a provided type alias for Rc<T> by default, but becomes Arc<T> when the async feature is enabled. Rc<T> and Arc<T> are also allowed anywhere ServiceRef<T> is allowed. For every injected type T, the appropriate ServiceDependency configuration is also added so that injected types can be validated.

The following is an advanced example with all of these concepts applied:

```rust trait Logger { fn log(&self, message: &str); }

trait Translator { fn translate(&self, text: &str, lang: &str) -> String; }

[injectable(Bar)]

impl BarImpl { #[inject] fn create( foo: ServiceRef, translator: Option>, loggers: Vec>) -> Self { Self { foo: foo, translator, loggers: loggers, } } } ```

Figure 6: Advanced Injectable configuration

Which will expand to:

rust impl Injectable for BarImpl { fn inject(lifetime: ServiceLifetime) -> ServiceDescriptor { ServiceDescriptorBuilder::<dyn Bar, Self>::new(lifetime, Type::of::<Self>()) .depends_on(ServiceDependency::new(Type::of::<dyn Foo>(), ServiceCardinality::ExactlyOne)) .depends_on(ServiceDependency::new(Type::of::<dyn Translator>(), ServiceCardinality::ZeroOrOne)) .depends_on(ServiceDependency::new(Type::of::<dyn Logger>(), ServiceCardinality::ZeroOrMore)) .from(|sp| Rc::new( BarImpl::create( sp.get_required::<dyn Foo>(), sp.get::<dyn Translator>(), sp.get_all::<dyn Logger>().collect()))) } }

Figure 7: Advanced Injectable implementation

Simplified Registration

Blanket implementations are provided for:

This simplifies registration to:

```rust fn main() { let provider = ServiceCollection::new() .add(FooImpl::singleton()) .add(BarImpl::transient()) .build_provider() .unwrap();

let bar = provider.get_required::<dyn Bar>();
let text = bar.speak();

assert_eq!(text, "foo bar")

} ``` Figure 8: inject feature usage

License

This project is licensed under the [MIT license].