Expand description
A minimal dependency-injection container for Rust.
Injectium provides a runtime DI container built around providers.
Providers can be closure-backed providers, shared values registered as
Arc<T>, or explicit value providers created with cloned / copied.
§Quick Start
use injectium_core::{Container, container, copied};
// Build a container with providers
let c = container! {
providers: [
copied(42_u32),
|c: &Container| format!("value is {}", c.get::<u32>()),
],
};
assert_eq!(c.get::<u32>(), 42);
assert_eq!(c.get::<String>(), "value is 42");§Using #[derive(Injectable)]
The injectium crate (not this one) re-exports
the #[derive(Injectable)] macro which automatically implements the
Injectable trait for your structs:
ⓘ
use injectium::{Injectable, container};
use std::sync::Arc;
#[derive(Clone, Injectable)]
struct Db {
conn: Arc<Connection>,
}
#[derive(Clone, Injectable)]
struct Config {
url: String,
}
#[derive(Injectable)]
struct Service {
db: Db,
config: Config,
}
// At application startup:
let c = container! {
providers: [
Arc::new(Connection::new()),
Config { url: "localhost".into() },
],
};
// Anywhere in your code, resolve a fully-constructed Service:
let svc = Service::from_container(&c);§Validation
Call Container::validate at startup to ensure every
#[derive(Injectable)] struct’s dependencies are actually registered:
ⓘ
let c = container! { /* ... */ };
c.validate(); // panics with a helpful message if something is missingThis catches misconfiguration immediately rather than failing on first use.
Re-exports§
pub use inventory;
Macros§
- container
- Declarative macro for building a container from providers.
- declare_
dependency - Declare that a type
$tymust be present in theContainer.
Structs§
- Clone
Provider - An explicit provider that clones a stored value on each request.
- Container
- A runtime dependency-injection container.
- Container
Builder - A builder for
Container. - Copy
Provider - An explicit provider that copies a stored value on each request.
- Declared
Dependency - A dependency declaration collected at link time via
inventory.
Traits§
- Injectable
- Types that can construct themselves from a
Container. - Provider
- A source that can provide values from a
Container. - Sync
Bounds