Skip to main content

Container

Struct Container 

Source
pub struct Container { /* private fields */ }
Expand description

The dependency injection container.

The container holds the typed singleton store, the provider registry, and registered destructors for #[injectable(pre_destruct)] hooks. It is constructed via Container::builder().

§Resolution Strategy

  • Types implementing Injectable are resolved via static providers
  • Types registered via ContainerBuilder::register() are resolved via the dynamic provider registry
  • All other types return MissingDependency errors

§Lifecycle

§Example

// Types you own: derive Injectable
#[injectable]
#[derive(Default)]
pub struct UserService { ... }

// Types you don't own: register a provider
let container = Container::builder()
    .register(DynProvider::new(|| {
        Ok(reqwest::Client::new())
    }))
    .build()
    .await?;

let service = container.resolve::<UserService>().await?;
let client = container.resolve_external::<reqwest::Client>().await?;

// On shutdown, call pre_destruct hooks
container.shutdown().await;

Implementations§

Source§

impl Container

Source

pub fn builder() -> ContainerBuilder

Create a new container builder.

Source

pub async fn resolve<T: Injectable>(&self) -> InjectableResult<T>

Resolve a type that implements Injectable.

This is the primary resolution method for types you own that use #[injectable].

§Example
let service = app.resolve::<UserService>().await?;
Source

pub async fn resolve_external<T: Send + Sync + 'static>( &self, ) -> InjectableResult<T>

Resolve an external type from the provider registry.

Use this for types that don’t implement Injectable but have been registered via ContainerBuilder::register.

§Example
let client = app.resolve_external::<reqwest::Client>().await?;
Source

pub async fn resolve_external_with_token<T: Send + Sync + 'static>( &self, token: &str, ) -> InjectableResult<T>

Resolve a named external type by token.

Use this when multiple providers of the same type were registered with different tokens via ContainerBuilder::register("token", DynProvider::…).

§Example
let primary: Pool = container.resolve_external_with_token("primary").await?;
let replica:  Pool = container.resolve_external_with_token("replica").await?;
Source

pub async fn try_resolve_external_with_token<T: Send + Sync + 'static>( &self, token: &str, ) -> InjectableResult<Option<T>>

Resolve a named external type by token, returning None if not registered.

Source

pub fn context(&self) -> &ResolveContext

Get a reference to the internal resolve context.

Useful for manual extraction in advanced scenarios.

Source

pub fn registered_types(&self) -> Vec<&'static str>

Returns the names of all #[injectable] types registered in the container.

This includes every type that was annotated with #[injectable] and linked into the binary — useful for debugging MissingDependency errors and asserting DI registration in tests.

§Example
let container = Container::builder().build().await?;
assert!(container.registered_types().contains(&"Database"));
Source

pub async fn try_resolve<T: Injectable>(&self) -> InjectableResult<Option<T>>

Resolve a type, returning None instead of an error if it is not registered.

Maps MissingDependency → Ok(None) and propagates all other errors.

Source

pub async fn try_resolve_external<T: Send + Sync + 'static>( &self, ) -> InjectableResult<Option<T>>

Resolve an external type, returning None instead of an error if not registered.

Source

pub async fn shutdown(&self) -> InjectableResult<()>

Shut down the container, running all #[injectable(pre_destruct)] hooks.

Hooks are called in reverse construction order — the most recently constructed instance is destroyed first. This ensures that dependencies are not destroyed before the types that depend on them.

All destructors are called even if some fail (best-effort cleanup). If any hooks fail, returns InjectableError::ShutdownFailed containing all accumulated errors.

§Example
let container = Container::builder()
    .build()
    .await?;

let service = container.resolve::<Database>().await?;

// On application shutdown:
container.shutdown().await?;
Source

pub async fn destructor_count(&self) -> usize

Returns the number of registered destructors.

This counts instances that have #[injectable(has_pre_destruct)] and have been resolved through this container.

Trait Implementations§

Source§

impl Clone for Container

Source§

fn clone(&self) -> Container

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Container

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.