Expand description
§service-rs
An async-first, lightweight dependency injection (DI) container for Rust.
This library provides a simple and ergonomic way to manage dependencies in your Rust applications, inspired by Microsoft.Extensions.DependencyInjection.
§Features
- Three service lifetimes: Singleton, Scoped, and Transient
- Async-first design: All service resolution is async using
tokio - Thread-safe: Services are wrapped in
Arc<T>for safe sharing across threads - Automatic dependency injection: Use the
#[derive(Injectable)]macro for automatic constructor injection - Trait object support: Register implementations for trait objects
- Scoped services: Create service scopes with scoped lifetime management
§Service Lifetimes
- Singleton: One instance created and shared across the entire application
- Scoped: One instance per scope; same instance within a scope, new instance for each scope
- Transient: New instance created every time the service is requested
§Example
use service_rs::ServiceCollection;
use std::sync::Arc;
#[tokio::main]
async fn main() {
let mut collection = ServiceCollection::new();
collection.add_singleton_with_factory::<i32, _, _>(|_| async {
Ok(Box::new(42) as Box<dyn std::any::Any + Send + Sync>)
});
let provider = collection.build();
let num: Arc<i32> = provider.get::<i32>().await.unwrap();
assert_eq!(*num, 42);
}Structs§
- Scoped
Service Provider - A scoped service provider for resolving scoped services.
- Service
Collection - A collection of service descriptors used to build a service provider.
- Service
Descriptor - Internal descriptor that stores service registration information.
- Service
Provider - The root service provider for resolving services.
Enums§
- Service
Error - Errors that can occur during service registration and resolution.
- Service
Lifetime - Defines the lifetime of a service in the dependency injection container.
- Service
Provider Context - Context passed to service factories to enable dependency resolution.
Traits§
- Injectable
Extension - Extension trait for types that can be automatically injected.
Type Aliases§
- Service
Factory - A factory function that creates service instances.
Derive Macros§
- Injectable
- Derives the
Injectabletrait for automatic dependency injection.