dilib - Dependency Injection in Rust

80 points NeoCiber

I want to share dilib a library I started for fun, experimenting to achieve dependency injection in Rust, which is more easy in languagues with access to reflection.

Does Rust need dependency injection?

Not sure, I only asked could I? but never should I? but is handy in others frameworks like (C#) Entity Framework and (Java) Spring.

Example

// feature: full
use dilib::{inject, provide, resolve, Singleton, global::init_container};

#[provide]
fn get_repeat_count() -> usize {
    3
}

#[provide]
#[inject(s, name = "word")]
fn get_string(repeat_count: usize, s: Singleton<String>) -> String {
    s.repeat(repeat_count)
}

fn main() {
    init_container(|container| {
        // Additional deps
        container.add_singleton_with_name("word", String::from("nice!")).unwrap();
    }).unwrap();

    let s = resolve!(String).unwrap().cloned();
    assert_eq!(s, "nice!nice!nice!");
}