Thanks to visit codestin.com
Credit goes to docs.rs

Crate service_rs

Crate service_rs 

Source
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§

ScopedServiceProvider
A scoped service provider for resolving scoped services.
ServiceCollection
A collection of service descriptors used to build a service provider.
ServiceDescriptor
Internal descriptor that stores service registration information.
ServiceProvider
The root service provider for resolving services.

Enums§

ServiceError
Errors that can occur during service registration and resolution.
ServiceLifetime
Defines the lifetime of a service in the dependency injection container.
ServiceProviderContext
Context passed to service factories to enable dependency resolution.

Traits§

InjectableExtension
Extension trait for types that can be automatically injected.

Type Aliases§

ServiceFactory
A factory function that creates service instances.

Derive Macros§

Injectable
Derives the Injectable trait for automatic dependency injection.