simple_di/
lib.rs

1use std::sync::Arc;
2
3mod container;
4mod macros;
5
6/// Inject T instance from the DI container.
7///
8/// # Panics
9/// Panics if the type is not registered in the container.
10pub fn inject<T: 'static>() -> Arc<T> {
11    inject_optional().expect("Must be provided")
12}
13
14/// Inject T instance from the DI container.
15///
16/// Returns `None` if the type is not registered in the container.
17pub fn inject_optional<T: 'static>() -> Option<Arc<T>> {
18    container::get_sized_item()
19}
20
21#[doc(hidden)]
22pub mod __private {
23    use std::{any::TypeId, sync::Arc};
24
25    pub fn inject_unsized<T: ?Sized + 'static>() -> Arc<T> {
26        inject_unsized_optional().expect("Must be provided")
27    }
28
29    pub fn inject_unsized_optional<T: ?Sized + 'static>() -> Option<Arc<T>> {
30        crate::container::get_unsized_item()
31    }
32
33    pub fn provide_sized<T: Send + Sync + 'static>(item: Arc<T>) {
34        let previous = crate::container::set_item(TypeId::of::<T>(), item);
35        if let Some(previous) = previous {
36            drop(previous.to_arc_sized::<T>(false));
37        }
38    }
39
40    pub fn provide_unsized<T: Send + Sync + ?Sized + 'static>(item: Arc<T>) {
41        let previous = crate::container::set_item(TypeId::of::<T>(), item);
42        if let Some(previous) = previous {
43            drop(previous.to_arc_unsized::<T>(false));
44        }
45    }
46}