Expand description
Application hosting and dependency injection.
use hosting::{Service, ServiceCollection, abstraction};
use std::sync::Arc;
#[derive(Service)]
struct Database;
#[derive(Service)]
struct Repository {
db: Arc<Database>,
}
#[abstraction]
trait Notifier: Send + Sync {
fn notify(&self, message: &str);
}
#[derive(Service)]
struct Email;
impl Notifier for Email {
fn notify(&self, _message: &str) {}
}
#[derive(Service)]
struct Signup {
repository: Arc<Repository>,
notifiers: Vec<Arc<dyn Notifier>>,
}
let mut services = ServiceCollection::new();
services
.add_singleton::<Database>()
.add_scoped::<Repository>()
.add_singleton_as::<dyn Notifier, Email>()
.add_transient::<Signup>();
let provider = services.build()?;
let scope = provider.create_scope();
let signup = scope.resolve::<Signup>()?;
for notifier in &signup.notifiers {
notifier.notify("welcome");
}Structs§
- Build
Error - The service collection was rejected by
build. - Dependency
- A service another service needs in order to be constructed.
- Host
- A built application host.
- Host
Builder - Configures and builds a
Host. - Resolver
- Resolves dependencies while a service is being constructed.
- Scope
- A unit of work with its own scoped instances, such as one request.
- Service
Collection - Services registered for an application, frozen into a
ServiceProviderbybuild. - Service
Provider - The root of a built container. Cheap to clone.
Enums§
- Build
Issue - A single problem found while building a service collection.
- Lifetime
- How long a resolved instance is reused.
- Resolve
Error - Why a service could not be resolved.
Traits§
- Cast
From - Converts an implementation into the trait object it is registered as.
- Service
- A type the container can construct.
Type Aliases§
- BoxError
- Boxed error type accepted from constructors and factories.
Attribute Macros§
- abstraction
- Lets implementations of a trait be registered as
dyn Trait.
Derive Macros§
- Service
- Derives
Servicefor a struct.