Crate dependency_injector

Crate dependency_injector 

Source
Expand description

§Armature DI - High-Performance Dependency Injection for Rust

A lightning-fast, type-safe dependency injection container optimized for real-world web framework usage.

§Features

  • Lock-free - Uses DashMap for concurrent access without blocking
  • 🔒 Type-safe - Compile-time type checking with zero runtime overhead
  • 🚀 Zero-config - Any Send + Sync + 'static type is automatically injectable
  • 🔄 Scoped containers - Hierarchical scopes with full parent chain resolution
  • 🏭 Lazy singletons - Services created on first access
  • ♻️ Transient services - Fresh instance on every resolve
  • 🧵 Thread-local cache - Hot path optimization for frequently accessed services
  • 📊 Observable - Optional tracing integration with JSON or pretty output

§Quick Start

use dependency_injector::Container;

// Any Send + Sync + 'static type works - no boilerplate!
#[derive(Clone)]
struct Database {
    url: String,
}

#[derive(Clone)]
struct UserService {
    db: Database,
}

let container = Container::new();

// Register services
container.singleton(Database { url: "postgres://localhost".into() });
container.singleton(UserService {
    db: Database { url: "postgres://localhost".into() }
});

// Resolve - returns Arc<T> for zero-copy sharing
let db = container.get::<Database>().unwrap();
let users = container.get::<UserService>().unwrap();

§Service Lifetimes

use dependency_injector::Container;
use std::sync::atomic::{AtomicU64, Ordering};

static COUNTER: AtomicU64 = AtomicU64::new(0);

#[derive(Clone, Default)]
struct Config { debug: bool }

#[derive(Clone)]
struct RequestId(u64);

let container = Container::new();

// Singleton - one instance, shared everywhere
container.singleton(Config { debug: true });

// Lazy singleton - created on first access
container.lazy(|| Config { debug: false });

// Transient - new instance every time
container.transient(|| RequestId(COUNTER.fetch_add(1, Ordering::SeqCst)));

§Scoped Containers

use dependency_injector::Container;

#[derive(Clone)]
struct AppConfig { name: String }

#[derive(Clone)]
struct RequestContext { id: String }

// Root container with app-wide services
let root = Container::new();
root.singleton(AppConfig { name: "MyApp".into() });

// Per-request scope - inherits from root
let request_scope = root.scope();
request_scope.singleton(RequestContext { id: "req-123".into() });

// Request scope can access root services
assert!(request_scope.contains::<AppConfig>());
assert!(request_scope.contains::<RequestContext>());

// Root cannot access request-scoped services
assert!(!root.contains::<RequestContext>());

§Performance

  • Lock-free reads: Using DashMap for ~10x faster concurrent access vs RwLock
  • AHash: Faster hashing for TypeId keys
  • Thread-local cache: Avoid map lookups for hot services
  • Zero allocation resolve: Returns Arc<T> directly, no cloning

Modules§

logging
Logging configuration for dependency-injector
prelude
Prelude for convenient imports
typed
Compile-Time Type-Safe Container Builder
verified
Verified Service Providers

Macros§

debug
Constructs an event at the debug level.
error
Constructs an event at the error level.
info
Constructs an event at the info level.
provider
Helper macro to create a provider registration
trace
Constructs an event at the trace level.
warn
Constructs an event at the warn level.

Structs§

Arc
A thread-safe reference-counting pointer. ‘Arc’ stands for ‘Atomically Reference Counted’.
BatchBuilder
Fluent batch registration builder.
BatchRegistrar
Batch registrar for closure-based bulk registration.
Container
High-performance dependency injection container.
LazyFactory
Lazy singleton factory - creates instance on first access
PooledScope
A scope acquired from a pool that automatically returns when dropped.
ProviderRegistration
Registration information for a provider (used by module system)
Scope
Unique scope identifier.
ScopeBuilder
Builder for creating scoped containers with pre-configured services.
ScopePool
A pool of pre-allocated scopes for high-throughput scenarios.
ScopedContainer
A container with an associated scope identifier.
SingletonFactory
Singleton factory - stores a single pre-created instance
TransientFactory
Transient factory - creates new instance every time

Enums§

DiError
Errors that can occur during dependency injection operations
Lifetime
Service lifetime specification

Traits§

Factory
A factory that creates service instances (trait for external extensibility)
Injectable
Marker trait for types that can be injected via the DI container.
Provider
Backward compatibility alias

Type Aliases§

Result
Result type alias for DI operations