简体   繁体   中英

How model circular dependency in dagger2?

How can I model circular dependency using dagger2? Lets say we have only two classes. First injection is via constructor and second is via method as in example below:

class A{
    private B b;

    @Inject
    public A(B b)
    {
        this.b = b;
    }
}

class B{
    private A a;

    @Inject
    public B() { }

    @Inject
    public void injectA(A a)
    {
        this.a = a;
    }
}

You can use lazy injection:

class B{
    private Lazy<A> a;

    @Inject
    public B(Lazy<A> a) {
       this.a = a;
    }
}

Alternatively you can inject Provider<A> , but be aware that provider returns new instance of A each time Provider::get is invoked (assuming default scope), while Lazy::get returns the same instance.

Inject a Provider<A> or Provider<B> into one of them instead of an A or B directly. Then as long as the two classes don't both need the other in the constructor it will work. If they both need each other in their constructors, then there's no way to do it.

To my knowledge you can't.

Dependencies like this indicate that A and B might be tighter than they should be. Either merge them or refactor out the common part in C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM