Ferrous DI
An enterprise-grade, type-safe dependency injection framework for Rust with advanced features including async support, AOP patterns, module systems, and comprehensive reliability mechanisms.
Features
Core DI Features
- Type-safe: Full compile-time type checking with zero runtime reflection
- High Performance: ~78ns singleton resolution, O(1) service lookups
- Thread-safe: All APIs are
Send + Syncwith lock-free hot paths - Service Lifetimes: Singleton, Scoped, and Transient with proper isolation
- Trait Support: Single bindings and multi-bindings for trait objects
- Circular Detection: Comprehensive cycle detection with detailed error paths
- Memory Safe: Arc-based sharing with automatic cleanup
Advanced Features
- Async Support: Async factories, lifecycle management, and disposal
- AOP (Aspect-Oriented Programming): Method interception and decoration
- Module System: Hierarchical service organization and configuration
- Diagnostics: Service graph export, debugging tools, and telemetry
- Reliability: Circuit breakers, retries, and fault tolerance patterns
- Web Integration: Framework-agnostic patterns for web applications
- Agent Architecture: Durable agent patterns with state management
- Performance Monitoring: Built-in metrics and performance tracking
Quality & Reliability
- Professional Release Process: Semantic versioning with migration guides
- Comprehensive Testing: 200+ tests including mutation and fuzz testing
- Security Auditing: Regular dependency and vulnerability scanning
- Performance Benchmarking: Automated regression detection
- API Stability: Multi-tier stability guarantees with clear deprecation policies
Quick Start
Add ferrous-di to your Cargo.toml:
[]
= "0.1"
# With performance optimizations
= { = "0.1", = ["performance"] }
# With async support
= { = "0.1", = ["async"] }
# With diagnostics and debugging
= { = "0.1", = ["diagnostics"] }
# All features enabled
= { = "0.1", = ["performance", "async", "diagnostics"] }
Basic Usage
use ;
use Arc;
// Define your services
;
// Configure services
let mut services = new;
// Register singleton
services.add_singleton;
// Register with factory
services.;
// Register trait
services.;
// Build provider
let provider = services.build;
// Resolve services
let db = provider.;
let logger = provider.;
// Create scope for scoped services
let scope = provider.create_scope;
let user_service = scope.;
Service Lifetimes
Singleton
Single instance per root provider, cached forever:
services.add_singleton;
services.;
Scoped
Single instance per scope, cached for scope lifetime:
services.;
let scope = provider.create_scope;
let ctx1 = scope.; // Creates new
let ctx2 = scope.; // Returns same instance
Transient
New instance per resolution, never cached:
services.;
Trait Support
Single Binding (Replace Semantics)
;
// Register trait implementation
services.;
// Resolve single implementation
let email_service = provider.;
Multi-Binding (Append Semantics)
// Register multiple implementations
services.;
services.;
services.;
// Resolve all implementations
let plugins = provider..unwrap;
for plugin in plugins
Error Handling
Ferrous DI provides detailed error information:
use DiError;
match provider.
For convenience, use the get_required_* methods that panic on error:
let service = provider.; // Panics if not found
let trait_service = provider.;
Advanced Examples
Web Server with Request Scoping
See examples/web_server_scope.rs for a complete example showing:
- Singleton services (database, configuration)
- Scoped services (request context, user session)
- Dependency injection in request handlers
- Proper scope isolation per HTTP request
Modular Service Registration
See examples/modular_registration.rs for advanced patterns:
Durable Agent Architecture
See examples/durable-agent/ for a complete agent system:
Async Service Patterns
use AsyncFactory;
// Async service factory
;
services.add_async_singleton_factory;
AOP and Service Decoration
use ServiceDecorator;
// Logging decorator
services.;
Complex Dependency Graphs
services.add_singleton;
services.;
services.;
services.;
Module-Based Organization
use Module;
// Database module
;
// Application composition
let mut services = new;
services.add_module?;
services.add_module?;
services.add_module?;
Performance
Ferrous DI is designed for high-performance dependency injection with enterprise-grade capabilities.
Benchmark Results
Measured on Apple Silicon, compiled with --release:
| Operation | Time | Notes |
|---|---|---|
| Singleton hit | ~78ns | Cached singleton resolution (hot path) |
| Singleton cold | ~437ns | First-time singleton creation with factory |
| Scoped hit | ~83ns | Cached scoped service within same scope |
| Transient | ~68ns | Fresh instance creation each time |
| Concrete vs Trait | ~86ns vs ~82ns | Minimal difference between concrete and trait |
| Multi-binding (16 services) | ~850ns | Resolving all 16 implementations |
| Scope create/drop | ~18ns | Empty scope lifecycle overhead |
| Circular detection (depth 8) | ~87ns | Deep dependency chain validation |
| Using pattern (empty) | ~152ns | Minimal overhead for scoped disposal |
| Mixed workload | ~872ns | Realistic 70/20/10 singleton/scoped/transient mix |
Contention Performance
| Threads | Time per Op | Throughput | Scaling |
|---|---|---|---|
| 1 thread | ~79ns | ~12.6M ops/sec | Baseline |
| 2 threads | ~155ns | ~12.9M ops/sec total | Good parallelization |
| 4 threads | ~206ns | ~19.4M ops/sec total | Continued scaling |
| 8 threads | ~168ns | ~47.6M ops/sec total | Excellent multi-core utilization |
Performance Features
Enable high-performance optimizations with Cargo features:
[]
= { = "0.1", = ["performance"] }
This enables all performance features:
parking-lot: Faster mutex implementation (2-3x faster locking)ahash: High-performance hashing algorithmsmallvec: Stack-allocated vectors for small circular detection stacksonce-cell: Lock-free singleton caching (planned)
Individual Features
Enable features selectively if you prefer:
[]
= { = "0.1", = ["parking-lot", "ahash"] }
Reproduction Instructions
To reproduce benchmarks on your hardware:
# Clone the repository
# Run benchmarks with performance features
# Run specific benchmarks
# Generate HTML reports (if gnuplot available)
Performance Optimizations
The library implements several performance optimizations:
- TypeId-based lookups: O(1) service resolution using TypeId hash keys
- Arc-based sharing: Zero-copy service instance sharing
- Minimal allocations: Pre-allocated vectors, stack-allocated small collections
- Lock optimization: Parking-lot mutexes for reduced contention
- Hash optimization: AHash for faster HashMap operations
- Hot path optimization: Singleton resolution avoids locks when possible
Release Profile
The library is optimized with aggressive release settings:
[]
= 3
= "fat"
= 1
= false
This provides maximum performance for production use.
Feature Flags
Core Features
std (default)
Standard library support with std collections and threading:
[]
= "0.1" # includes std by default
async
Enable async factories and lifecycle management:
[]
= { = "0.1", = ["async"] }
use AsyncFactory;
// Async service creation
services.add_async_singleton_factory;
let connection = provider..await?;
Performance Features
performance
Enable all performance optimizations:
[]
= { = "0.1", = ["performance"] }
Individual performance features:
parking-lot: Faster mutex implementation (2-3x faster locking)ahash: High-performance hashing algorithmsmallvec: Stack-allocated vectors for small collectionsonce-cell: Lock-free singleton caching (experimental)
Development Features
diagnostics
Enable comprehensive debugging and diagnostic tools:
[]
= { = "0.1", = ["diagnostics"] }
validation
Enable service validation and health checks:
[]
= { = "0.1", = ["validation"] }
Integration Features
web
Web framework integration patterns:
[]
= { = "0.1", = ["web"] }
metrics
Built-in metrics and telemetry:
[]
= { = "0.1", = ["metrics"] }
Experimental Features
experimental
Cutting-edge features under development:
[]
= { = "0.1", = ["experimental"] }
โ ๏ธ Note: Experimental features may change or be removed in minor versions.
Testing & Quality Assurance
Running Tests
Run the complete test suite:
Run specific test categories:
Quality Gates
Mutation Testing
Test the quality of your tests with mutation testing:
Fuzzing
Run property-based and fuzz testing:
Security Auditing
Scan for security vulnerabilities:
Performance Benchmarking
Run performance benchmarks:
Code Coverage
Generate code coverage reports:
Development Roadmap
Completed Features โ
- Phase 1: Modular architecture with 25+ specialized modules
- Phase 2: Comprehensive CI/CD with multi-platform testing
- Phase 3: Complete documentation with examples and guides
- Phase 4: Advanced development tools and diagnostics
- Phase 5: Comprehensive testing (unit, integration, mutation, fuzz)
- Phase 6: Performance optimization and production readiness
- Phase 7: Professional release engineering process
Current & Upcoming Features ๐ง
- Phase 8: Advanced agent features with state persistence
- Phase 9: Ecosystem integration and framework adapters
- Phase 10: API stabilization and v1.0 preparation
Version Releases
- v0.1: Core DI with lifetimes, traits, circular detection โ
- v0.2: Async support, AOP patterns, module system
- v0.3: Advanced diagnostics, reliability patterns
- v0.4: Web integration, performance optimizations
- v0.5: Agent architecture, state management
- v1.0: Stable API, comprehensive ecosystem integration
Long-term Vision
- Enterprise Integration: Support for complex enterprise patterns
- Framework Ecosystem: Deep integration with popular Rust frameworks
- Cloud Native: Kubernetes, service mesh, and cloud platform support
- Tooling Ecosystem: IDE extensions, debugging tools, and analysis
See ROADMAP.md for detailed feature plans and timelines.
Contributing
We welcome contributions from the community! This project follows professional development practices:
Getting Started
- Read CONTRIBUTING.md for detailed guidelines
- Check CODE_OF_CONDUCT.md for community standards
- Review ARCHITECTURE.md to understand the codebase
Development Process
- Quality Gates: All PRs must pass comprehensive testing and validation
- Conventional Commits: Follow conventional commit format for automatic changelog generation
- API Stability: Review API_STABILITY.md for compatibility requirements
- Release Process: Understand our professional release engineering in RELEASE_CHECKLIST.md
Areas for Contribution
- ๐ Bug Fixes: Help improve reliability and correctness
- ๐ Performance: Optimize hot paths and memory usage
- ๐ Documentation: Improve examples, guides, and API docs
- ๐งช Testing: Add test coverage, property tests, or benchmarks
- ๐ง Tooling: IDE integration, debugging tools, or analysis
- ๐ Integration: Framework adapters and ecosystem support
Security
For security vulnerabilities, please see SECURITY.md for responsible disclosure.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
Project Status
Ferrous DI is actively developed and maintained with professional development practices:
- ๐๏ธ Architecture: Enterprise-grade modular design
- ๐งช Testing: 200+ tests with comprehensive coverage
- ๐ Documentation: Complete API docs and examples
- ๐ Performance: Production-ready with benchmarking
- ๐ Security: Regular auditing and vulnerability scanning
- ๐ Quality: Professional release process with validation
- ๐ค Community: Open source with contributor guidelines
Ready for Production: Suitable for enterprise applications requiring high performance, reliability, and maintainability.
For questions, issues, or contributions, visit our GitHub repository.
Architecture & Design Philosophy
Comparison with Microsoft.Extensions.DependencyInjection
| Feature | Ferrous DI | MS.DI | Notes |
|---|---|---|---|
| Type Safety | Compile-time | Runtime | Zero-cost abstractions vs reflection |
| Performance | ~78ns resolution | ~1000ns+ | TypeId-based O(1) lookups |
| Memory Safety | Built-in Arc sharing | Manual lifecycle | Rust ownership + Arc |
| Async Support | Native async/await | Task-based | First-class async factories |
| Lifetimes | Singleton, Scoped, Transient | Same | Compatible lifecycle semantics |
| Multi-binding | Explicit append semantics | Implicit append | Clear intention |
| Circular Detection | Compile + Runtime | Runtime | Multi-layered protection |
| Thread Safety | Lock-free hot paths | Thread-safe | Optimized for concurrent access |
| Modularity | Hierarchical modules | Service collections | Advanced composition |
| Diagnostics | Built-in graph export | Limited | Rich debugging capabilities |
| AOP Support | Native decoration | Third-party | Built-in interception |
| Reliability | Circuit breakers, retries | Manual | Enterprise patterns |
Design Principles
- Zero-Cost Abstractions: Compile-time optimization with runtime efficiency
- Memory Safety: Rust ownership system prevents common DI pitfalls
- Performance First: Designed for high-throughput, low-latency applications
- Enterprise Ready: Professional patterns for complex applications
- Developer Experience: Rich diagnostics and clear error messages
- Ecosystem Integration: Framework-agnostic with deep integration support
Unique Features
- Agent Architecture: Durable agent patterns with state management
- Module System: Hierarchical service organization and configuration
- Performance Monitoring: Built-in metrics and telemetry
- Reliability Patterns: Circuit breakers, retries, and fault tolerance
- Professional Release Process: Enterprise-grade release engineering
- Comprehensive Testing: Mutation testing, fuzzing, and property-based testing