- 🚀 Async-first architecture (factory-based, scoped resolution)
- 🧠 Lifetimes: Singleton, Scoped, Transient
- 📛 Named service instances
- 💡 Declarative registration via #[rust_di::registry(...)]
- 🔁 Task-local isolation (tokio::task_local!)
- 🧰 Procedural macros with zero boilerplate
- 🧪 Circular dependency detection
- 📦 Thread-safe (using Arc, RwLock, DashMap, ArcSwap, OnceCell)
[dependencies]
rust_di = { version = "3.1.1" }#[derive(Default)]
pub struct Logger;
#[rust_di::registry(
Singleton,
Singleton(factory),
Singleton(name = "file_logger"),
Singleton(name = "console_logger"),
Singleton(name = "email_logger", factory = EmailLoggerFactory),
Transient,
Transient(factory),
Transient(name = "file_logger"),
Transient(name = "console_logger"),
Transient(name = "email_logger", factory = EmailLoggerFactory),
Scoped,
Scoped(factory),
Scoped(name = "file_logger"),
Scoped(name = "console_logger"),
Scoped(name = "email_logger", factory = EmailLoggerFactory),
)]
impl Logger {
pub fn log(&self, msg: &str) {
println!("{}", msg);
}
}Before resolving any services, make sure to initialize the DI system:
#[tokio::main]
async fn main() {
rust_di::initialize().await;
}- All services declared via inventory::submit!
- Global singletons & factories
- Internal caches and resolving state
#[tokio::main]
async fn main() {
rust_di::initialize().await;
rust_di::DIScope::run_with_scope(|| async {
let di = rust_di::DIScope::current().unwrap();
let logger = di.clone().get::<Logger>().await.unwrap();
logger.log("Hello!");
let file_logger = di.get_by_name::<Logger>("file").await.unwrap();
file_logger.log("Writing to file...");
}).await;
}Use #[rust_di::main] to simplify your async fn main. It ensures:
- ✅ rust_di::initialize().await
- ✅ DIScope::run_with_scope(...)
- ✅ DI services available from the start
#[rust_di::main]
#[tokio::main]
async fn main() {
let scope = rust_di::DIScope::current().unwrap();
let logger = scope.get::<Logger>().await.unwrap();
logger.log("Started!");
}async fn, not on trait methods or functions wrapped with conflicting attribute macros such as #[tokio::main] or
#[test].
async fn entrypoints, background workers, or utility functions where full DI context is needed.
#[rust_di::with_di_scope]
async fn consume_queue() {
let di = DIScope::current().unwrap();
let consumer = di.get::<Consumer>().await.unwrap();
consumer.run().await;
}This pattern is ideal for long-running background tasks, workers, or event handlers that need access to scoped services.
- Eliminates boilerplate around
DIScope::run_with_scope - Ensures
task-localvariables are properly initialized - Works seamlessly in
main,background loops, or anyasync entrypoint - Encourages
clean, scoped service resolution
use rust_di::DIScope;
use rust_di::core::error_di::DiError;
use rust_di::core::factory::DiFactory;
use rust_di::registry;
use std::sync::Arc;
#[derive(Default)]
pub struct Logger;
#[registry(Singleton)]
impl Logger {}
pub struct Processor {
pub logger: Arc<Logger>,
}
#[registry(Singleton(factory))]
impl Processor {}
#[async_trait::async_trait]
impl DiFactory for Processor {
async fn create(scope: Arc<DIScope>) -> Result<Self, DiError> {
let logger = scope.get::<Logger>().await?;
Ok(Processor {
logger: logger.clone(),
})
}
}- 🔧 Resolves dependencies with async precision
- 🎯 Keeps instantiation logic colocated
- 🧩 Enables complex composition across lifetimes
In some situations—like ordering guarantees, test injection, or dynamic setup—you may want to bypass macros and register manually:
use rust_di::DIScope;
use rust_di::core::error_di::DiError;
use rust_di::core::registry::register_singleton_name;
#[derive(Default)]
pub struct Logger;
#[tokio::main]
async fn main() -> Result<(), DiError> {
rust_di::initialize().await;
// Manual registration
register_singleton_name::<Logger, _, _>("file", |_| async { Ok(Logger::default()) }).await?;
DIScope::run_with_scope(|| async {
let di = DIScope::current().unwrap();
let logger = di.get_by_name::<Logger>("file").await?;
logger.log("Manual registration works!");
Ok(())
}).await
}Function Description register_singleton unnamed global instance register_singleton_name(name) named global instance register_scope_name(name) scoped factory register_transient_name(name) re-created per request
| Function | Description |
|---|---|
| register_transient | re-created per request |
| register_transient_name | named re-created per request |
| register_scope | scoped factory |
| register_scope_name | named scoped factory |
| register_singleton | unnamed global instance |
| register_singleton_name | named global instance |
📚 These extensions give you full control—whether bootstrapping large systems, injecting mocks in tests, or dynamically assembling modules.
- Services stored as
Arc<T> - Global state managed via
OnceCell&ArcSwap - Scope-local cache via
DashMap - Panics on usage outside active DI scope
- Circular dependency errors on recursive resolutions
| Lifetime | Behavior |
|---|---|
| Singleton | One instance per App. Global, shared across all scopes |
| Scoped | Created one instance per DIScope::run_with_scope() |
| Transient | New instance every time Re-created on every .get() |
Supports:
- Singleton, Scoped, Transient
- factory — use
DiFactoryorcustom factory - name = "..." — register named instance
- All services are stored as
Arc<T> - Internally uses
DashMap,ArcSwap, andOnceCell Task-localisolation viatokio::task_local!
Because DIScope relies on task-local variables (tokio::task_local!), spawning a new task with tokio::spawn will
lose the current DI scope context.
tokio::spawn( async {
// ❌ This will panic: no DI scope found
let scope = DIScope::current().unwrap();
});If you need to spawn a task that uses DI, wrap the task in a new scope:
tokio::spawn( async {
rust_di::DIScope::run_with_scope(|| async {
let scope = di::DIScope::current().unwrap();
let logger = scope.get::< Logger > ().await.unwrap();
logger.log("Inside spawned task");
}).await;
});Alternatively, pass the resolved dependencies into the task before spawning.
This project aims to show support for Ukraine and its people amidst a war that has been ongoing since 2014. This war has a genocidal nature and has led to the deaths of thousands, injuries to millions, and significant property damage. We believe that the international community should focus on supporting Ukraine and ensuring security and freedom for its people.
Join us and show your support using the hashtag #StandForUkraine. Together, we can help bring attention to the issues faced by Ukraine and provide aid.