simple-di

Crates.iosimple-di
lib.rssimple-di
version0.1.1
sourcesrc
created_at2024-06-01 20:57:05.905614
updated_at2024-06-03 07:26:31.023806
descriptionSimple dependency injection for Rust
homepage
repositoryhttps://github.com/bingo347/rust-simple-di
max_upload_size
id1258875
size14,718
Dmitry Belyaev (bingo347)

documentation

README

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");
    }
}
Commit count: 9

cargo fmt