#traits #dyn #injection #object #inject #registry

nightly dyn_inject

Rust dependency injection that works with trait objects

1 unstable release

0.1.0 Apr 23, 2023

#30 in #inject

Apache-2.0

6KB
65 lines

dyn_inject

This crates provides utilities for dependency injection in Rust, also supporting dyn Trait trait objects instead of only static, sized types.

Example

use dyn_inject::Registry;

trait Foo {
    fn foo();
}

struct Bar;

impl Foo for Bar {
    fn foo() {
        println!("Hello");
    }
}

fn main() {
    let mut registry = Registry::new();
    registry.put_dyn::<dyn Foo>(Bar);
    // Calls Bar::foo()
    registry.get_dyn::<dyn Foo>().unwrap().foo()
}

lib.rs:

This crates provides utilities for dependency injection in Rust, also supporting dyn Trait trait objects instead of only static, sized types.

Example

use dyn_inject::Registry;

trait Foo {
    fn foo();
}

struct Bar;

impl Foo for Bar {
    fn foo() {
        println!("Hello");
    }
}

fn main() {
    let mut registry = Registry::new();
    registry.put_dyn::<dyn Foo>(Bar);
    // Calls Bar::foo()
    registry.get_dyn::<dyn Foo>().unwrap().foo();
}

No runtime deps