Skip to content

nintha/autowired-rs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Autowired

crates.io docs.rs

Rust dependency injection project, inspired by Spring IOC.

Add Dependency

[dependencies]
autowired="0.1"

Usage

Just derive your struct with the marco Component, you can use the singleton component everywhere.

#[derive(Default, Component)]
struct Bar {
    name: String,
    age: u32,
}

fn main() {
    // create `bar` via Default::default
    let bar: Autowired<Bar> = Autowired::new();

    assert_eq!(String::default(), bar.name);
    assert_eq!(u32::default(), bar.age);
}

Define custom component initialization logic

#[derive(Default)]
struct Foo {
    value: String,
}

impl Component for Foo {
    type Error = ();

    fn new_instance() -> Result<Arc<Self>, Self::Error> {
        Ok(Arc::new(Foo {
            value: TEST_STRING.to_string(),
        }))
    }
}

fn main() {
    // create `foo` via new_instance
    let foo = Autowired::<Foo>::new();

    assert_eq!("TEST_STRING", foo.value);
}

Central registration in the beginning of the program

By default, components are registered lazily. If you need to register components in advance at the beginning of the program, you can refer to this example:

use autowired::{Component, Bean, setup_submitted_beans};

#[derive(Default, Component, Bean)]
struct Foo;

#[derive(Default, Component, Bean)]
struct Bar;

fn main() {
    // register components which derives `Bean`
    setup_submitted_beans();

    assert!(autowired::exist_component::<Foo>());
    assert!(autowired::exist_component::<Bar>());
}