pub struct Container { /* private fields */ }Expand description
Dependency injection container
Stores services as Arc-wrapped values and provides type-safe retrieval. Services are singletons - only one instance exists per type.
§Example
ⓘ
let mut container = Container::new();
container.register(Arc::new(DatabaseService::new()));
let db: Arc<DatabaseService> = container.resolve().unwrap();Implementations§
Source§impl Container
impl Container
Sourcepub fn register<T: Injectable>(&mut self, service: Arc<T>)
pub fn register<T: Injectable>(&mut self, service: Arc<T>)
Sourcepub fn register_factory<T: Injectable, F>(&mut self, factory: F)where
F: FnOnce() -> T,
pub fn register_factory<T: Injectable, F>(&mut self, factory: F)where
F: FnOnce() -> T,
Sourcepub async fn register_async_factory<T, F, Fut>(
&mut self,
factory: F,
) -> Result<()>
pub async fn register_async_factory<T, F, Fut>( &mut self, factory: F, ) -> Result<()>
Register a service from an async constructor function.
Use this for services that require async initialization — database
connections, config loading from remote sources, etc. The async effect
is contained here; once registered, the service is a plain Arc<T>
and all subsequent framework operations remain synchronous.
Returns Err if the factory future resolves to an error.
§Example
ⓘ
container
.register_async_factory(|| async {
let db = Database::connect("postgres://localhost/mydb").await?;
Ok(DbService::new(db))
})
.await?;Sourcepub fn resolve<T: Injectable>(&self) -> Option<Arc<T>>
pub fn resolve<T: Injectable>(&self) -> Option<Arc<T>>
Sourcepub fn resolve_or_panic<T: Injectable>(&self) -> Arc<T>
pub fn resolve_or_panic<T: Injectable>(&self) -> Arc<T>
Sourcepub fn contains<T: Injectable>(&self) -> bool
pub fn contains<T: Injectable>(&self) -> bool
Check if a service is registered
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Container
impl !RefUnwindSafe for Container
impl Send for Container
impl Sync for Container
impl Unpin for Container
impl UnsafeUnpin for Container
impl !UnwindSafe for Container
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more