pub struct Container { /* private fields */ }Expand description
A runtime dependency-injection container.
Container stores one provider per type.
A provider can be a closure that constructs a fresh value, or an [Arc]
that clones and returns shared state. Consumers use get
to retrieve an owned value regardless of how that provider is implemented.
Containers are built through ContainerBuilder (or the
container! macro) and are typically wrapped in an
Arc for sharing across threads.
§Example
use injectium_core::{Container, container};
let c = container! {
providers: [|_: &Container| 42_u32, |_: &Container| "hello"],
};
assert_eq!(c.get::<u32>(), 42);
assert_eq!(c.get::<&str>(), "hello");Implementations§
Source§impl Container
impl Container
Sourcepub fn builder() -> ContainerBuilder
pub fn builder() -> ContainerBuilder
Returns a new ContainerBuilder.
Equivalent to ContainerBuilder::new.
Sourcepub fn builder_with_capacity(capacity: usize) -> ContainerBuilder
pub fn builder_with_capacity(capacity: usize) -> ContainerBuilder
Returns a new ContainerBuilder with preallocated storage capacity.
Sourcepub fn get<T: SyncBounds>(&self) -> T
pub fn get<T: SyncBounds>(&self) -> T
Sourcepub fn try_get<T: SyncBounds>(&self) -> Option<T>
pub fn try_get<T: SyncBounds>(&self) -> Option<T>
Returns the current value for type T, or None if no provider is
registered.
Sourcepub fn validate(&self)
pub fn validate(&self)
Validates that every dependency declared via declare_dependency! is
registered in this container.
Available when the validation feature is enabled.
Intended to be called once at application startup, immediately after the container is built. If any declared dependency is absent, the method panics with a message that lists every missing type by name, making misconfiguration easy to diagnose.
#[derive(Injectable)] automatically calls declare_dependency! for
each field type, so this check covers all structs that use the derive
macro without any manual bookkeeping.
§Panics
Panics if one or more declared dependencies are not registered, printing the names of all missing types.
Sourcepub fn provider_count(&self) -> usize
pub fn provider_count(&self) -> usize
Returns the number of registered providers.