luminos Container
A lightweight dependency injection container for Rust, designed to manage services, factories, and singletons with type-safe bindings. This container supports binding factories, registering singletons, and resolving instances, making it suitable for building modular and testable applications.
Features
- Type-Safe Bindings: Bind factories to create instances of specific types.
- Singleton Support: Register singletons to ensure a single instance is reused.
- Transient Factories: Create new instances on each resolution.
- Service Providers: Register and boot service providers for modular configuration.
- Dynamic Resolution: Resolve instances by type using
TypeId.
Usage
The Container struct is the core of the library. Below are examples demonstrating how to use its key functionalities.
Setup
Create a new Container instance:
use Container;
let mut container = new;
Binding a Factory
Bind a factory to create new instances of a type (transient instances):
container.bind;
Resolve a transient instance:
let instance = container.transient.unwrap;
let service = instance..unwrap;
assert_eq!;
Registering a Singleton
Register a singleton instance to ensure only one instance is created and reused:
let type_id = ;
container.singleton;
let instance = container.resolve_any.unwrap;
let service = instance..unwrap;
assert_eq!;
// Subsequent resolutions return the same instance
let instance2 = container.resolve_any.unwrap;
assert_eq!;
Using a Singleton Factory
Register a singleton via a factory, which is executed once to create the instance:
let type_id = ;
let factory = ;
container.singleton_factory;
let instance = container.resolve_any.unwrap;
let service = instance..unwrap;
assert_eq!;
// Same instance is reused
let instance2 = container.resolve_any.unwrap;
assert_eq!;
Registering Service Providers
Service providers allow modular configuration of the container:
use ServiceProvider;
;
container.register_provider;
container.boot;
Notes
- Singletons are stored separately from transient services to ensure proper instance management.
- The container uses
TypeIdfor type-safe resolution, so ensure types are unique and correctly registered. - Factories are executed each time for transient resolutions but only once for singleton factories.
Testing
The library includes a comprehensive test suite to verify the behavior of bindings, singletons, and service providers. To run the tests:
License
This project is licensed under the MIT License.