A minimal, zero-dependency dependency-injection container for Rust.
Injectium provides a runtime DI container with two registration strategies:
- Singletons – a single instance shared across all consumers.
- Factories – a closure that produces a fresh instance on each request.
Quick Start
use ;
// Build a container with singletons and/or factories
let c = container! ;
// Retrieve a singleton
assert_eq!;
// Resolve a factory (produces a new value each time)
assert_eq!;
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! {
singletons: [
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 missing
This catches misconfiguration immediately rather than failing on first use.