9 stable releases

3.1.0 Dec 20, 2023
3.0.0 Nov 24, 2023
2.1.2 Aug 14, 2023
2.1.1 Apr 11, 2023
1.0.0 Sep 27, 2022

#245 in Rust patterns

Download history 24/week @ 2024-07-20 41/week @ 2024-07-27 19/week @ 2024-08-03 19/week @ 2024-08-10 414/week @ 2024-08-17 51/week @ 2024-08-24 57/week @ 2024-08-31 22/week @ 2024-09-07 23/week @ 2024-09-14 74/week @ 2024-09-21 37/week @ 2024-09-28 100/week @ 2024-10-05 339/week @ 2024-10-12 74/week @ 2024-10-19 74/week @ 2024-10-26 33/week @ 2024-11-02

538 downloads per month
Used in 4 crates

MIT license

140KB
3K SLoC

More Dependency Injection   CI Crates.io MIT licensed

More DI is a dependency injection (DI) library for Rust. A trait or struct can be used as the injected type.

You may be looking for:

Features

This crate provides the following features:

  • default - Abstractions for dependency injection, plus the builder and inject features
  • builder - Functions for configuring service descriptors
  • async - Use dependencies in an asynchronous context
  • inject - Code-generate common injection scenarios
  • lazy - Lazy-initialize service resolution
  • fmt - Additional output formatting
  • alias - Use alternate type aliases

Supported Lifetimes

A service can have the following lifetimes:

  • Transient - a new instance is created every time it is requested
  • Singleton - a single, new instance is created the first time it is requested
  • Scoped - a new instance is created once per provider that it is requested from

Dependency Injection in Action

Consider the following traits and structures.

Proc macro attributes are not required, but they are the fastest and simplest approach to add DI in your applications.

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

trait Phrase {
    fn salutation(&self) -> &str;
}

#[injectable(Phrase)]
struct EnglishPhase;

impl Phrase for EnglishPhrase {
    fn salutation(&self) -> &str {
        "Hello world!"
    }
}

#[injectable]
struct Person {
    phase: Rc<dyn Phrase>,
}

impl Person {
    fn speak(&self) -> &str {
        self.phrase.salutation()
    }
}

This information can now be composed into a simple application:

use crate::*;
use di::*;

fn main() {
    let provider = ServiceCollection::new()
        .add(EnglishPhrase::singleton())
        .add(Person::transient())
        .build_provider()
        .unwrap();

    let person = provider.get_required::<Person>();

    println!("{}", person.speak());
}

License

This project is licensed under the MIT license.

Dependencies

~0.1–10MB
~47K SLoC