Skip to main content

Crate hosting

Crate hosting 

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

BuildError
The service collection was rejected by build.
Dependency
A service another service needs in order to be constructed.
Host
A built application host.
HostBuilder
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.
ServiceCollection
Services registered for an application, frozen into a ServiceProvider by build.
ServiceProvider
The root of a built container. Cheap to clone.

Enums§

BuildIssue
A single problem found while building a service collection.
Lifetime
How long a resolved instance is reused.
ResolveError
Why a service could not be resolved.

Traits§

CastFrom
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 Service for a struct.