mod container;
mod inject;
pub use container::{Container, ContainerBuilder, DeclaredDependency};
pub use inject::Injectable;
#[macro_export]
macro_rules! container {
(singletons: [$( $singleton:expr ),* $(,)?] $(,)? providers: [$( $factory:expr ),* $(,)?] $(,)?) => {{
$crate::Container::builder()
$(.singleton($singleton))*
$(.factory($factory))*
.build()
}};
(singletons: [$( $singleton:expr ),* $(,)?] $(,)?) => {{
$crate::Container::builder()
$(.singleton($singleton))*
.build()
}};
(providers: [$( $factory:expr ),* $(,)?] $(,)?) => {{
$crate::Container::builder()
$(.factory($factory))*
.build()
}};
}
#[cfg(test)]
mod tests {
#[test]
fn empty_both() {
let c = container! {
singletons: [],
providers: []
};
assert_eq!(c.singleton_count(), 0);
assert_eq!(c.factory_count(), 0);
}
#[test]
fn only_singletons() {
let c = container! {
singletons: [1_u32, 2_u64],
providers: []
};
assert_eq!(c.singleton_count(), 2);
assert_eq!(c.factory_count(), 0);
}
#[test]
fn only_providers() {
let c = container! {
singletons: [],
providers: [
|_c| 42_u32,
|_c| "hello",
]
};
assert_eq!(c.singleton_count(), 0);
assert_eq!(c.factory_count(), 2);
}
#[test]
fn only_singletons_no_providers_key() {
let c = container! {
singletons: [1_u32, 2_u64]
};
assert_eq!(c.singleton_count(), 2);
assert_eq!(c.factory_count(), 0);
}
#[test]
fn only_singletons_no_providers_key_empty() {
let c = container! {
singletons: []
};
assert_eq!(c.singleton_count(), 0);
assert_eq!(c.factory_count(), 0);
}
#[test]
fn only_singletons_no_providers_key_trailing_comma() {
let c = container! {
singletons: [1_u32,],
};
assert_eq!(c.singleton_count(), 1);
assert_eq!(c.factory_count(), 0);
}
#[test]
fn only_providers_no_singletons_key() {
let c = container! {
providers: [|_c| 42_u32, |_c| "hello"]
};
assert_eq!(c.singleton_count(), 0);
assert_eq!(c.factory_count(), 2);
}
#[test]
fn only_providers_no_singletons_key_empty() {
let c = container! {
providers: []
};
assert_eq!(c.singleton_count(), 0);
assert_eq!(c.factory_count(), 0);
}
#[test]
fn only_providers_no_singletons_key_trailing_comma() {
let c = container! {
providers: [|_c| 42_u32,],
};
assert_eq!(c.singleton_count(), 0);
assert_eq!(c.factory_count(), 1);
}
#[test]
fn singletons_and_providers() {
let c = container! {
singletons: [1_u32],
providers: [|_c| 99_u64]
};
assert_eq!(c.singleton_count(), 1);
assert_eq!(c.factory_count(), 1);
assert_eq!(*c.get::<u32>(), 1);
assert_eq!(c.resolve::<u64>(), 99);
}
#[test]
fn trailing_commas() {
let c = container! {
singletons: [1_u32,],
providers: [|_c| 2_u64,],
};
assert_eq!(c.singleton_count(), 1);
assert_eq!(c.factory_count(), 1);
}
}