Runtime dependency injection library for Rust
[](https://crates.io/crates/dill) [](https://github.com/sergiimk/dill-rs/actions) [](https://deps.rs/repo/github/sergiimk/dill-rs)
This crate is still in early stages and needs a lot of work, BUT it's in active use in kamu-cli
- a fairly large project organized according to Onion/Clean Architecture. We are continuing to improve this crate as we go and encounter more sophisticated DI scenarios.
```rust /////////////////////////////////////////
// Define interfaces in traits trait A: Send + Sync { fn test(&self) -> String; }
// Implement traits to define components
struct AImpl {
// Auto-inject dependencies (also supports by-value)
b: Arc
impl A for AImpl { fn test(&self) -> String { format!("aimpl::{}", self.b.test()) } }
/////////////////////////////////////////
trait B: Send + Sync { fn test(&self) -> String; }
struct BImpl;
impl B for BImpl { fn test(&self) -> String { "bimpl".to_owned() } }
/////////////////////////////////////////
// Register interfaces and bind them to implementations
let cat = CatalogBuilder::new()
.add::
// Get objects and have their deps satisfied automatically
let inst = cat.get::
OneOf
- expects a single implementation of a given interfaceAllOf
- returns a collection of all implementations on a given interfaceMaybe<Spec>
- Returns None
if inner Spec
cannot be resolvedTransient
(default) - a new instance is created for every invocationSingleton
- an instance is created upon first use and then reused for the rest of calls#[component]
macro can derive Builder
:
struct
or on impl
block with Impl::new()
functionArc<T>
, T: Clone
, &T
Option<T>
is interpreted as OneOf<T>
specVec<T>
is interpreted as AllOf<T>
specBuilder
Clone
typesCatalog
can be self-injectedstable
rustScope
s external to Builder
s so they could be overriddenArc
, Option
, Vec
to dependency specs instead of relying on macro magictrybuild
tests (see https://youtu.be/geovSK3wMB8?t=956)add_*
with generic add<B: Into<Builder>>
Arc<dyn Iface>
can be hidden behind a movable object
dyn Trait
(e.g. accepting impl AsRef<str>
parameters instead of &str
)