Skip to main content

di_container

Attribute Macro di_container 

Source
#[di_container]
Expand description

Compile-time dependency injection container

Generates a container with automatic dependency resolution at compile time.

§Attributes

  • #[provide(expr)] - Use custom expression for initialization
  • #[provide(from_env)] - Load from environment using FromEnv trait
  • #[provide(singleton)] - Shared instance (default)
  • #[provide(transient)] - New instance on each access
  • #[provide(async)] - Async initialization using AsyncInit trait
  • #[depends(field1, field2)] - Explicit dependencies

§Example (Sync)

#[di_container]
struct AppContainer {
    database: DatabaseService,
    repository: UserRepository,
}

let container = AppContainer::new();

§Example (Async)

#[di_container]
struct AppContainer {
    #[provide(from_env)]
    config: Config,

    #[provide(singleton, async)]
    #[depends(config)]
    database: DatabasePool,

    #[provide(transient)]
    service: MyService,
}

let container = AppContainer::build().await?;