he_di 0.2.1

Dependency Inversion / Dependency Injection / Inversion of control container for Rust
Documentation
#![allow(non_snake_case)]

extern crate he_di;
#[macro_use] extern crate he_di_derive;

use he_di::ContainerBuilder;
use he_di::Error as DIError;
use he_di::container::ValidatorError;

trait Foo : ::std::fmt::Debug {
    fn foo(&self);
}

#[derive(Component, Debug)]
#[interface(Foo)]
struct FooImpl {
    value: String,
}

#[derive(Component, Debug)]
#[interface(Foo)]
struct AnotherFooImpl {
    value: String,
}

impl Foo for FooImpl {
    fn foo(&self) {
        println!("FooImpl > foo > value = {}", self.value);
    }
}

impl Foo for AnotherFooImpl {
    fn foo(&self) {
        println!("AnotherFooImpl > foo > value = {}", self.value);
    }
}

// Registration of the 2nd Component should overwrite the first entry
// Since we can only have 1 Component of the same interface
#[test]
fn trying_to_register_several_components_with_the_same_type_should_fail() {
    let mut builder = ContainerBuilder::new();
    builder.register::<FooImpl>()
        .as_type::<Foo>()
        .with_named_parameter("value", "value 1".to_string());
    builder.register::<AnotherFooImpl>()
        .as_type::<Foo>()
        .with_named_parameter("value", "value 2".to_string());

    let container = builder.build();
    assert!(&container.is_err());
    if let DIError::RegistrationError(ValidatorError::MultipleErrors(errs)) = container.unwrap_err() {
        assert_eq!(errs.len(), 2);

        let expected_err = ValidatorError::IllegalValue("duplicate entry: multiple components are registered to type Foo > AnotherFooImpl".to_string());
        assert!(errs.iter().find(|err| err == &&expected_err).is_some());

        let expected_err = ValidatorError::IllegalValue("duplicate entry: multiple components are registered to type Foo > FooImpl".to_string());
        assert!(errs.iter().find(|err| err == &&expected_err).is_some());
    } else {
        panic!("invalid state > container should be a RegistrationError");
    }
}