SaDi - Semi-automatic Dependency Injector
A lightweight, type-safe dependency injection container for Rust applications. SaDi provides both transient and singleton service registration with automatic dependency resolution and circular dependency detection.
โจ Features
- ๐ Type-Safe: Leverages Rust's type system for compile-time safety
- ๐ Transient Services: Create new instances on each request
- ๐ Singleton Services: Shared instances with reference counting
- ๐ Circular Detection: Prevents infinite loops in dependency graphs
- โ Error Handling: Comprehensive error types with detailed messages
- ๐ Optional Logging: Tracing integration with feature gates
- ๐ Zero-Cost Abstractions: Feature gates enable compile-time optimization
๐ฆ Installation
Add this to your Cargo.toml:
[]
= "0.1.2"
# Optional: Enable tracing support
= { = "0.1.2", = ["tracing"] }
๐ Quick Start
use SaDi;
use Rc;
// Define your services
๐ Usage Guide
Service Registration
Transient Services
Create new instances on each request:
use SaDi;
let container = new
.factory;
// Each call creates a new logger with different session_id
let logger1 = container.;
let logger2 = container.;
Singleton Services
Create once and share across all dependents:
use SaDi;
use Rc;
let container = new
.factory_singleton;
// Both calls return the same instance
let config1 = container.;
let config2 = container.;
assert_eq!;
Error Handling
SaDi provides both panicking and non-panicking variants:
use ;
let container = new
.factory;
// Panicking version (use when you're sure service exists)
let service = container.;
// Non-panicking version (returns Result)
match container.
// Trying to get unregistered service
match container.
Dependency Injection
Services can depend on other services:
use SaDi;
use Rc;
let container = new
.factory_singleton
.factory_singleton
.factory;
let repo = container.;
๐ Advanced Features
Circular Dependency Detection
SaDi automatically detects and prevents circular dependencies:
use SaDi;
// This will panic with detailed error message
let container = new
.factory
.factory;
// This panics: "Circular dependency detected: ServiceA -> ServiceB -> ServiceA"
let service = container.;
Tracing Integration
Enable the tracing feature for automatic logging:
[]
= { = "0.1.2", = ["tracing"] }
use SaDi;
use info;
async
๐งช Testing
Run the test suite:
# Run all tests
# Run with tracing feature
# Run documentation tests
# Run example
๐ Project Structure
sadi/
โโโ src/
โ โโโ lib.rs # Library entry point
โ โโโ sadi.rs # Core DI container implementation
โโโ examples/
โ โโโ basic/ # Comprehensive usage example
โโโ README.md # This file
๐ง Configuration
Feature Flags
tracing- Enable tracing/logging support (optional)
Environment Variables
When using the tracing feature, you can control logging levels:
# Set log level
RUST_LOG=debug
# Enable only SaDi logs
RUST_LOG=sadi=info
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Development Setup
- Clone the repository:
- Run tests:
- Check formatting:
- Run clippy:
๐ Roadmap & TODO
๐ Async Support
- Async Factory Functions: Support for
async fnfactories - Async Service Resolution: Non-blocking service creation
- Async Singleton Caching: Thread-safe async singleton management
- Async Circular Detection: Proper handling in async contexts
๐งต Thread Safety
- Arc-based Container: Thread-safe version of SaDi using
Arcinstead ofRc - Send + Sync Services: Support for services that implement
Send + Sync - Concurrent Access: Multiple threads accessing services simultaneously
- Lock-free Operations: Minimize contention in high-concurrency scenarios
๐ง Advanced Features
- Service Scoping: Request-scoped, thread-scoped service lifetimes
- Lazy Initialization: Defer singleton creation until first access
- Service Decorators: Middleware/decoration patterns for services
- Conditional Registration: Register services based on runtime conditions
- Service Health Checks: Built-in health monitoring for services
- Service Metrics: Performance and usage statistics
- Hot Reloading: Dynamic service replacement without container restart
๐ฆ Ecosystem Integration
- Tokio Integration: First-class support for Tokio runtime
- Actix-web Plugin: Direct integration with Actix-web framework
- Axum Integration: Support for Axum web framework
- Tower Service: Implement Tower service trait
- Serde Support: Serialize/deserialize container configuration
๐ ๏ธ Developer Experience
- Derive Macros: Auto-generate factory functions from service structs
- Builder Validation: Compile-time validation of dependency graphs
- Error Suggestions: Better error messages with fix suggestions
- IDE Integration: Language server support for dependency analysis
- Container Visualization: Graphical representation of service dependencies
๐ Security & Reliability
- Service Isolation: Sandboxing for untrusted services
- Resource Limits: Memory and CPU limits per service
- Graceful Shutdown: Proper cleanup on container disposal
- Fault Tolerance: Circuit breaker pattern for failing services
๐ Observability
- OpenTelemetry: Built-in telemetry and distributed tracing
- Prometheus Metrics: Expose container metrics for monitoring
- Service Discovery: Integration with service discovery systems
- Health Endpoints: HTTP endpoints for container health checks
๐ฏ Performance
- Compile-time DI: Zero-runtime-cost dependency injection
- Service Pooling: Object pooling for expensive-to-create services
- Memory Optimization: Reduced memory footprint for large containers
- SIMD Optimizations: Vectorized operations where applicable
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- Inspired by dependency injection patterns from other languages and frameworks
- Built with โค๏ธ using Rust's powerful type system
- Thanks to the Rust community for excellent crates and documentation
Made with โค๏ธ by Joรฃo Pedro Martins