instancebuilder
Handy solution for dependency injection in Rust.
Installation
cargo add instancebuilder
Examples
Simple
use ::std::convert::Infallible;
use ::instancebuilder::{Error, InstanceBuilder, FromInstanceBuilder};
struct TestConfig {
key: String,
}
struct TestImplementation {
message: String,
}
impl FromInstanceBuilder for TestImplementation {
fn try_from_builder(builder: &InstanceBuilder) -> Result<Self, Error> {
let config: &TestConfig = builder.data()?;
Ok(Self {
message: config.key.clone(),
})
}
}
fn main() {
let config = TestConfig {
key: String::from("help me!"),
};
let mut builder = InstanceBuilder::new();
builder.insert(config);
let instance = builder.build::<TestImplementation>().unwrap();
}
Nested dependencies
use ::std::convert::Infallible;
use ::instancebuilder::{Error, InstanceBuilder, FromInstanceBuilder};
struct TestConfig {
key: String,
}
struct InnerTestImplementation {
message: String,
}
impl FromInstanceBuilder for InnerTestImplementation {
fn try_from_builder(builder: &InstanceBuilder) -> Result<Self, Error> {
let config: &TestConfig = builder.data()?;
Ok(Self {
message: config.key.clone(),
})
}
}
struct OuterTestImplementation {
inner: InnerTestImplementation,
}
impl FromInstanceBuilder for OuterTestImplementation {
fn try_from_builder(builder: &InstanceBuilder) -> Result<Self, Error> {
Ok(Self {
inner: builder.build()?,
})
}
}
fn main() {
let config = TestConfig {
key: String::from("help me!"),
};
let mut builder = InstanceBuilder::new();
builder.insert(config);
let instance = builder.build::<OuterTestImplementation>().unwrap();
}