Coi provides an easy to use dependency injection framework. Currently, this crate provides the following:
coi::Inject
(trait) - a marker trait that indicates a trait is injectable, and that a struct can be used to implement those injectable traits.coi::Provide
- a trait that indicates a struct is capable of providing a specific implementation of some injectable trait. This is generated for you if you use thecoi::Inject
(derive) derive, but can also be written manually.coi::Container
- a container to manage the lifetime of all dependencies. This is still in its early stages, and currently only supports objects that are recreated with each request to resolve.coi::ContainerBuilder
- a builder for the above container to simplify construction and guarantee immutability after construction.
Example
use async_std;
use ;
use Arc;
// Mark injectable traits by inheriting the `Inject` trait.
// For structs that will provide the implementation of an injectable trait, derive `Inject`
// and specify which method will be used to inject which trait. The method can be any path.
// The arguments for the method are derived from fields marked with the attribute `#[inject]`
// (See Impl2 below).
// Currently, only one trait can be provided, but this will likely be expanded on in future
// versions of this crate.
;
// The method specified in Provides must return Self (might change in a future version of the
// crate), and must actually exist (it will not be generated for you).
// Don't forget to actually implement the trait ;).
// Mark injectable traits by inheriting the `Inject` trait.
// For structs that will provide the implementation of an injectable trait, derive `Inject`
// and specify which method will be used to inject which trait. The arguments for the method
// are derived from fields marked with the attribute `#[inject]` in the order they appear.
// Future versions of this crate might allow you to control the order of the args with
// parameters to the `#[inject]` attribute.
// Implement the provider method
// Again, don't forget to actually implement the trait ;).
// You might note that Container::resolve is async. This is to allow any provider to be async
// and since we don't know from the resolution perspective whether any provider will need to be
// async, they all have to be. This might be configurable through feature flags in a future
// version of the library.
async