nicolascotton / nject

Simple zero cost dependency injection library made for rust
MIT License
45 stars 3 forks source link

How to handle cyclic case? #48

Open stevefan1999-personal opened 2 months ago

stevefan1999-personal commented 2 months ago

I want to inject DepTwo with DepOne, and DepOne with DepTwo, what should I do instead?

use std::sync::Arc;

use nject::{injectable, provider};

#[injectable]
#[derive(Debug)]
struct DepOne {
    dep: Arc<DepTwo>,
}

#[injectable]
#[derive(Debug)]
struct DepTwo {
    dep: Arc<DepOne>,
}

#[injectable]
#[derive(Debug)]
struct Facade {
    dep: Arc<DepTwo>,
}

#[provider]
#[provide(Arc<DepOne>, |two: Arc<DepTwo>| Arc::new(DepOne { dep: two }))]
#[provide(Arc<DepTwo>, |one: Arc<DepOne>| Arc::new(DepTwo { dep: one }))]
#[derive(Debug)]
struct Provider {}

fn main() {
    let _facade: Facade = Provider {}.provide();
    println!("{:?}", _facade.dep.dep.dep);
}

Currently overflows the stack.

nicolascotton commented 2 months ago

Hi @stevefan1999-personal,

If you had to manually inject the Facade, how would you do it?