There are one type can be provider of services: ServiceProvider. It used as store for dependencies with
Instance and Singleton lifetimes, and for declaring all dependencies using .add_*() methods. It can be forked to
create a local scope with local instances.
There are four lifetimes for dependencies:
Transient. Service will be created when resolves. Can depend on dependencies with anything lifetime.Singleton. Service will be created once atServiceProviderwhen it resolved (lazy). Can depend on dependencies with anything lifetime. Cannot depend on services from forkedServiceProviderinstances.Instance. Dependency was created outside ofServiceProviderand can be used by any other dependency.
How to work:
- Declare your structs.
- Create constructors and add
#[inject]macro on its. - Create a
ServiceProviderobject. - Add your services and dependencies using
ServiceProvider::add_*methods. - Fork
ServiceProviderif you need to create local scope. - Get service from provider using
.resolve()method. - Work with service.
Example:
use Rc;
use *;
// derive macro can be used when all fields implement `Dependency` trait,
// but we do not recommend use it in production code
// Create `ServiceProvider` struct that store itself all dependencies
let container = new
// Add dependency with `Singleton` lifetime. More about lifetimes see above.
.
// Add dependency with `Transient` lifetime. More about lifetimes see above.
.;
// Fork `ServiceProvider`. It creates a new `ServiceProvider` which will have
// access to the dependencies from parent `ServiceProvider`.
let scope = container
// .fork() method creates a local mutable scope with self parent immutable `ServiceProvider`.
.fork
// Add an instance of `Rc<i32>` that will be used when `ConstService` will be initialized.
.add_instance;
let controller: Controller = scope.resolve;
assert_eq!;