Skip to main content

ContainerBuilder

Struct ContainerBuilder 

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

Builder for constructing a Container.

The builder supports:

  • Registering dynamic providers for external types
  • Setting a custom singleton store
  • Startup validation

§Registering External Types

Use register to provide a closure-based provider for types you don’t control:

let container = Container::builder()
    // Simple: no dependencies
    .register(DynProvider::new(|| {
        Ok(reqwest::Client::new())
    }))
    // With context: depends on other injectables
    .register(DynProvider::with_ctx(|ctx| async move {
        let config = ctx.resolve::<AppConfig>().await?;
        Ok(sqlx::SqlitePool::connect(&config.db_url).await?)
    }))
    .build()
    .await?;

Then resolve with Container::resolve_external:

let client: reqwest::Client = container.resolve_external().await?;

Implementations§

Source§

impl ContainerBuilder

Source

pub fn new() -> Self

Create a new container builder.

Source

pub fn with_store(self, store: Arc<dyn SingletonStore>) -> Self

Set a custom singleton store for the container.

The store is typically auto-generated by the macro. Use this method only for custom store implementations.

Source

pub fn register<T: Send + Sync + 'static>( self, token: impl Into<String>, provider: DynProvider<T>, ) -> Self

Register a dynamic provider for an external type under the given token.

Every registration is keyed by (TypeId<T>, token), so multiple providers of the same type can coexist as long as they carry different tokens. Use DEFAULT_TOKEN ("") for the canonical, unnamed registration.

§Simple Registration (default token)
builder.register("", DynProvider::sync(|| Ok(reqwest::Client::new())));
// later:
let client = container.resolve_external::<reqwest::Client>().await?;
§Multiple Providers of the Same Type
builder
    .register("primary",  DynProvider::new(|| async { Ok(primary_pool()) }))
    .register("replica",  DynProvider::new(|| async { Ok(replica_pool()) }));
// later:
let primary: Pool = container.resolve_external_with_token("primary").await?;
let replica:  Pool = container.resolve_external_with_token("replica").await?;
§Context-Aware Registration
builder.register("", DynProvider::with_ctx(|ctx| async move {
    let config = ctx.extract::<Inject<AppConfig>>().await?;
    Ok(Database::connect(&config.db_url).await?)
}));
Source

pub fn register_or_replace<T: Send + Sync + 'static>( self, token: impl Into<String>, provider: DynProvider<T>, ) -> Self

Register a dynamic provider, silently replacing any existing provider for the same (type, token) pair.

Use this in tests or layered-config scenarios where you intentionally want to override an existing registration.

Source

pub async fn build(self) -> InjectableResult<Container>

Build the container.

This performs startup validation of the dependency graph (collected automatically from all #[injectable] and #[injectable] types via the inventory crate) and the singleton store, then returns a ready-to-use container.

§Validation

The dependency graph is validated at build time for:

  • Circular dependencies
  • Scope mismatches (singleton depending on transient)
  • Missing dependencies
  • Duplicate registrations

If any validation errors are found, the build fails with InjectableError::ConstructionFailed.

Trait Implementations§

Source§

impl Debug for ContainerBuilder

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for ContainerBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. 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> 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, 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.