2 releases
0.1.1 | Jun 3, 2024 |
---|---|
0.1.0 | Jun 1, 2024 |
#1389 in Rust patterns
78 downloads per month
8KB
126 lines
simple-di
Simple dependency injection for Rust
Example
use simple_di::{inject, inject_optional, provide};
struct Point {
x: f64,
y: f64,
}
trait GetX {
fn get_x(&self) -> f64;
}
trait GetY {
fn get_y(&self) -> f64;
}
impl GetX for Point {
fn get_x(&self) -> f64 {
self.x
}
}
impl GetY for Point {
fn get_y(&self) -> f64 {
self.y
}
}
fn main() {
let point = Point { x: 1.0, y: 2.0 };
provide!(point => GetX, GetY);
use_point();
use_get_x();
use_get_y();
}
fn use_point() {
let point = inject::<Point>();
let Point { x, y } = *point;
println!("x: {x}, y: {y}");
}
fn use_get_x() {
let abstract_get_x = inject!(GetX);
let x = abstract_get_x.get_x();
println!("x: {x}");
let abstract_get_x = inject_optional!(GetX);
if let Some(abstract_get_x) = abstract_get_x {
let x = abstract_get_x.get_x();
println!("x: {x}");
} else {
println!("GetX is not provided");
}
}
fn use_get_y() {
let abstract_get_y = inject!(GetY);
let y = abstract_get_y.get_y();
println!("y: {y}");
let abstract_get_y = inject_optional!(GetY);
if let Some(abstract_get_y) = abstract_get_y {
let y = abstract_get_y.get_y();
println!("y: {y}");
} else {
println!("GetY is not provided");
}
}
Dependencies
~0.9–6MB
~20K SLoC