This release represents a significant improvement in new and existing features.
Features
- Mutable services
- Keyed services
- Improved proc macro attribute injection
ScopedServiceProvider
allows for injecting a scopedServiceProvider
declaratively- Format (fmt) feature for printing and troubleshooting service mappings
- Aliases (alias) feature to allow user-defined injected type aliases
- User guide
- Relaxed
'static
lifetime requirements (where possible) - Lazy initialization functions (ex: for testing)
Improved #[injectable]
The #[injectable]
attribute proc macro can now also be applied to:
- A
struct
definition (not just theimpl
for a struct) - A tuple
struct
- A generic
struct
or tuplestruct
- A
struct
constructor can now useimpl Iterator<Item>
for any supported types ServiceProvider::create_scope()
is injected forScopedServiceProvider
The following illustrates a few examples.
use di::*;
use std::collections::HashMap;
trait Worker {
fn do_work(&self);
}
// apply directly to struct definition
#[injectable(Worker)]
struct WorkerImpl;
impl Worker for WorkerImpl {
fn do_work(&self) { }
}
// apply to tuple struct
#[injectable]
struct JobSite(Vec<Ref<dyn Worker>>);
// declaratively inject ServiceProvider.create_scope()
#[injectable]
struct RequestContext(ScopedServiceProvider);
trait Feature {
fn name(&self) -> &str;
}
struct Component {
features: HashSet<String, Ref<dyn Feature>>,
}
// inject sequence of services without allocating a Vec
#[injectable]
impl Component {
fn new(features: impl Iterator<Item = Ref<dyn Feature>>) -> Self {
Self {
features: features.map(|f| (f.name().into(), f.clone())).collect()
}
}
}
Mutable Services
Creating mutable services was previously possible to create, but required additional work by developers. Mutable services are now supported as a first class concept to simplify usage. Services are wrapped in RefCell
by default or in RwLock
when the async feature is activated.
let mut provider =
ServiceCollection::new()
.add(WokerImpl::transient().as_mut())
.build_provider()
.unwrap();
// RefMut<dyn Worker> == Ref<RefCell<dyn Worker> == Rc<RefCell<dyn Worker>>
let worker = provider.get_required_mut::<dyn Worker>();
Keyed Services
The need for keyed services should be an infrequent one, but the workaround to make it work in the past was painful. Keyed services now have formal support. Unlikely other DI frameworks, the key must be a type, which provides clarity, uniqueness, and supplants magic strings.
mod key {
struct Thing1;
struct Thing2;
}
trait Thing {}
#[injectable(Thing)]
struct FirstThing;
impl Thing for FirstThing {}
#[injectable(Thing)]
struct SecondThing;
impl Thing for SecondThing {}
#[injectable]
struct CatInTheHat {
thing1: KeyedRef<key::Thing1, dyn Thing>,
thing2: KeyedRef<key::Thing1, dyn Thing>,
}
fn main() {
let provider =
ServiceCollection::new()
.add(Thing1::transient().with_key<key::Thing1>())
.add(Thing2::transient().with_key<key::Thing2>())
.add(CatInTheHat::transient())
.build_provider()
.unwrap();
let cat_in_the_hat = provider.get_required::<CatInTheHat>();
}
For more details and examples, see the user guide.
Breaking Changes
Every effort is made to avoid breaking changes, but sometimes they are inevitable. Great care was taken to minimize the impact of breaking changes and make them source-compatible when possible.
Injectable Trait
Injectable::inject
now returns InjectBuilder
instead of ServiceDescriptor
. This change is required to enable a fluent builder to optionally configure a key and/or mutability. InjectBuilder
implements Into<ServiceDescriptor>
and ServiceCollection::add
now accepts T: Into<ServiceDescriptor>
, which will maintain source compatibility. Unless you implemented the Injectable
trait yourself, this change should be transparent.
ServicedDescriptorBuilder Struct
The ServicedDescriptorBuilder
struct has been moved into the builder feature. InjectBuilder
servers the same purpose and ServicedDescriptorBuilder
will typically only be used now if you also use the other builder functions.
ServiceRef Type Alias
The ServiceRef<T>
type alias has been replaced with Ref<T>
to make it more succinct. To avoid excessive code churn, you can redefine the old alias and it will work without any additional configuration; for example: type ServiceRef<T> = di::Ref<T>;
.
You may not like either the old or new type alias name, therefore, the new alias feature allows you to define whichever alias you like via the crate dependency configuration. You might want to use Svc<T>
instead of Ref<T>
. This can be achieved with the simple configuration:
[dependencies]
more-di = { version = "3.0", features = ["alias"], aliases { ref = "Svc" } }
This feature is only necessary if you are using #[injectable]
so that it recognizes the injected types; otherwise, it has no effect within the library. The user guide has additional details on how to configure custom type aliases.