crate, docs, repo, rocket integration
Shaku is a dependency injection library which I initially released earlier this month. Unlike most other Rust DI libraries, shaku has compile time guarantees and allows you to create both long living and temporary services.
This 0.2.0 release brings compile time DI guarantees, meaning all service dependencies and parameters will be checked during compilation (previously checked during app startup). The program will fail to compile if you don't supply a dependency/parameter or if you try to resolve a service which is not available. In addition, circular dependencies can be checked for at compile time.
Most of the work is taken care of by (optional) macros, so there is minimal boilerplate. See the getting started guide on the docs for a walkthrough!
use shaku::{module, Component, Container, ContainerBuilder, Interface};
use std::sync::Arc;
trait Output: Interface {
fn write(&self, content: String);
}
trait DateWriter: Interface {
fn write_date(&self);
}
#[derive(Component)]
#[shaku(interface = Output)]
struct ConsoleOutput;
impl Output for ConsoleOutput {
fn write(&self, content: String) {
println!("{}", content);
}
}
#[derive(Component)]
#[shaku(interface = DateWriter)]
struct TodayWriter {
#[shaku(inject)]
output: Arc<dyn Output>,
today: String,
year: usize,
}
impl DateWriter for TodayWriter {
fn write_date(&self) {
self.output.write(format!("Today is {}, {}", self.today, self.year));
}
}
module! {
MyModule {
components = [ConsoleOutput, TodayWriter],
providers = []
}
}
fn main() {
let container: Container<MyModule> = ContainerBuilder::new()
.with_component_parameters::<TodayWriter>(TodayWriterParameters {
today: "Feb 23".to_string(),
year: 2020
})
.build();
let writer: &dyn DateWriter = container.resolve_ref();
writer.write_date(); // Prints "Today is Feb 23, 2020"
}
I'm really interested in what you think of the API, usability, documentation, etc, so please open issues!