Expand description
§ferrous-di
Type-safe, performant dependency injection for Rust, inspired by Microsoft.Extensions.DependencyInjection.
§Features
- Type-safe lifetimes: Singleton, Scoped, and Transient services
- Trait support: Single and multi-binding trait resolution
- Thread-safe: Arc-based sharing with proper lifetime management
- Circular dependency detection: Prevents infinite loops with detailed error paths
- Scoped isolation: Request-scoped services with proper cleanup
- Zero-cost abstractions: Compile-time type safety with runtime performance
§Quick Start
use ferrous_di::{ServiceCollection, Resolver};
use std::sync::Arc;
// Define your services
struct Database {
connection_string: String,
}
struct UserService {
db: Arc<Database>,
}
// Register services
let mut services = ServiceCollection::new();
services.add_singleton(Database {
connection_string: "postgres://localhost".to_string(),
});
services.add_transient_factory::<UserService, _>(|resolver| {
UserService {
db: resolver.get_required::<Database>(),
}
});
// Build and use the service provider
let provider = services.build();
let user_service = provider.get_required::<UserService>();
assert_eq!(user_service.db.connection_string, "postgres://localhost");§Service Lifetimes
- Singleton: Created once and shared across the entire application
- Scoped: Created once per scope (ideal for web request contexts)
- Transient: Created fresh on every resolution
§Trait Resolution
use ferrous_di::{ServiceCollection, Resolver};
use std::sync::Arc;
trait Logger: Send + Sync {
fn log(&self, message: &str);
}
struct ConsoleLogger;
impl Logger for ConsoleLogger {
fn log(&self, message: &str) {
println!("[LOG] {}", message);
}
}
let mut services = ServiceCollection::new();
services.add_singleton_trait::<dyn Logger>(Arc::new(ConsoleLogger));
let provider = services.build();
let logger = provider.get_required_trait::<dyn Logger>();
logger.log("Hello, World!");§Scoped Services
use ferrous_di::{ServiceCollection, Resolver};
use std::sync::{Arc, Mutex};
struct RequestId(String);
let mut services = ServiceCollection::new();
let counter = Arc::new(Mutex::new(0));
let counter_clone = counter.clone();
services.add_scoped_factory::<RequestId, _>(move |_| {
let mut c = counter_clone.lock().unwrap();
*c += 1;
RequestId(format!("req-{}", *c))
});
let provider = services.build();
let scope1 = provider.create_scope();
let scope2 = provider.create_scope();
let req1 = scope1.get_required::<RequestId>();
let req2 = scope2.get_required::<RequestId>();
// Different scopes get different instancesRe-exports§
pub use collection::ServiceCollection;pub use collection::ServiceModule;pub use collection::ServiceCollectionExt;pub use collection::ServiceCollectionModuleExt;pub use provider::ServiceProvider;pub use provider::Scope;pub use provider::ScopedResolver;pub use provider::ResolverContext;pub use descriptors::ServiceDescriptor;pub use error::DiError;pub use error::DiResult;pub use key::Key;pub use key::key_of_type;pub use lifetime::Lifetime;pub use observer::DiObserver;pub use observer::LoggingObserver;pub use observer::ObservationContext;pub use observer::WorkflowObserver;pub use observer::WorkflowContextProvider;pub use observer::MetricsObserver;pub use prewarm::ReadyCheck;pub use prewarm::ReadinessResult;pub use prewarm::ReadinessReport;pub use scope_local::ScopeLocal;pub use scope_local::WorkflowContext;pub use scope_local::ScopeLocalBuilder;pub use scope_local::workflow;pub use capabilities::ToolCapability;pub use capabilities::CapabilityRequirement;pub use capabilities::ToolSelectionCriteria;pub use capabilities::ToolInfo;pub use capabilities::ToolDiscoveryResult;pub use validation::ValidationBuilder;pub use validation::ValidationResult;pub use validation::ValidationError;pub use validation::ValidationWarning;pub use fast_singletons::FastSingletonCache;pub use fast_singletons::FastSingletonMetrics;pub use traits::Dispose;pub use traits::AsyncDispose;pub use traits::Resolver;pub use traits::ResolverCore;pub use cancellation::CancellationToken;pub use cancellation::CancellationError;pub use cancellation::ScopeCancellationExt;pub use labeled_scopes::LabeledScope;pub use labeled_scopes::LabeledScopeExt;pub use labeled_scopes::LabeledScopeContext;pub use labeled_scopes::LabeledScopeRegistry;pub use labeled_scopes::ScopeMetadata;pub use decoration::ServiceDecorator;pub use decoration::TraitDecorator;pub use decoration::DecorationPipeline;pub use decoration::decorators;pub use graph_export::DependencyGraph;pub use graph_export::GraphNode;pub use graph_export::GraphEdge;pub use graph_export::GraphMetadata;pub use graph_export::GraphLayout;pub use graph_export::NodePosition;pub use graph_export::LayoutBounds;pub use graph_export::DependencyType;pub use graph_export::ExportOptions;pub use graph_export::ExportFormat;pub use graph_export::GraphBuilder;pub use graph_export::GraphExporter;pub use graph_export::DefaultGraphExporter;pub use graph_export::exports;pub use graph_export::workflow_integration;
Modules§
- cancellation
- Cancellation token support for workflow engines.
- capabilities
- Capability discovery and tool catalog functionality for agentic systems.
- collection
- Service collection module for dependency injection.
- decoration
- First-class decoration pipeline for service interception and modification.
- descriptors
- Service descriptors for introspection and diagnostics.
- error
- Error types for the dependency injection container.
- fast_
singletons - Fast-path singleton resolution with OnceCell and sharding for optimal performance.
- graph_
export - Graph export functionality for dependency visualization and UI integration.
- key
- Service key types for the dependency injection container.
- labeled_
scopes - Hierarchical labeled scopes for workflow engines.
- lifetime
- Service lifetime definitions.
- metrics
- Metrics collection and monitoring for ferrous-di performance.
- observer
- Diagnostic observers for dependency injection traceability.
- performance
- Performance optimization components for ferrous-di.
- prewarm
- Pre-warm and readiness functionality for deterministic agent startup.
- provider
- Service provider module for dependency injection.
- scope_
local - Scope-local context values for ergonomic per-run state.
- traits
- Core traits for the dependency injection container.
- validation
- Build-time lifetime validation for dependency injection configurations.
Macros§
- decorate
- Helper macro for creating simple function-based decorators.
- scope_
local - Convenience macro for accessing scope-local values with less boilerplate.
- validate_
services - Validates service registrations at compile time.
Structs§
- Circular
Panic - Panic payload for circular dependency detection.
- Options
- Immutable options wrapper that implements
IOptions<T>. - Options
Builder - Options builder for configuring complex options with dependencies.
Traits§
- IOptions
- Options interface for dependency injection.