rs-bean
A lightweight Rust library for bean management and dependency injection.
⚠️ APIs are not stable yet; future releases may introduce breaking changes.
Features
- Dependency Injection: Automatic dependency resolution and injection
- Scope Management: Support for Singleton and Prototype scopes
- Circular Dependency Detection: Detects and prevents circular dependencies with detailed error messages
- Type-safe: Leverages Rust's type system for compile-time safety
- Thread-safe: Built with
ArcandRwLockfor concurrent access - Named Beans: Register multiple beans of the same type with different names
- Zero External Dependencies: Pure Rust implementation using only std library
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Quick Start
use Arc;
use ;
// Define your services
Usage
Registering Beans
Default Registration (by Type)
// Singleton scope - single instance shared across all requests
container.?;
// Prototype scope - new instance created for each request
container.?;
Named Registration
// Register multiple beans of the same type with different names
container.?;
container.?;
Retrieving Beans
Get by Type
let service = container.?;
Get by Name
let primary_db = container.?;
let replica_db = container.?;
Dependency Injection
Dependencies are automatically resolved during bean creation:
container.?;
container.?;
container.?;
Circular Dependency Detection
The container automatically detects circular dependencies:
// This will fail with a clear error message
container.?;
container.?;
// Error: Circular dependency detected! Dependency path: Bean(ServiceA) -> Bean(ServiceB) -> Bean(ServiceA)
API Reference
BeanContainer
The main container for managing beans.
Methods
new() -> Self- Create a new bean containerregister<T, F>(scope: Scope, factory: F) -> Result<(), String>- Register a bean by typeregister_named<T, F>(name: &str, scope: Scope, factory: F) -> Result<(), String>- Register a named beanget<T>() -> Result<Arc<T>, String>- Get a bean by typeget_named<T>(name: &str) -> Result<Arc<T>, String>- Get a bean by namecontains<T>(name: Option<&str>) -> bool- Check if a bean existslen() -> usize- Get the number of registered beansis_empty() -> bool- Check if the container is empty
Scope
Bean lifecycle scope.
Scope::Singleton- Single instance shared across all requestsScope::Prototype- New instance created for each request
Dependencies
Provides access to other beans during bean creation.
Methods
get<T>() -> Result<Arc<T>, String>- Get a dependency by typeget_named<T>(name: Option<&str>) -> Result<Arc<T>, String>- Get a dependency by namecurrent_path() -> String- Get the current dependency resolution path (for debugging)
Examples
See the examples directory for more detailed examples:
- basic.rs - Basic usage with dependency injection
Run examples with:
License
MIT License
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.