aQuu
aQuu

Reputation: 565

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;
    }
}

Upvotes: 0

Views: 83

Answers (3)

Alex Filatov
Alex Filatov

Reputation: 5052

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.

Upvotes: 2

Gabe Sechan
Gabe Sechan

Reputation: 93599

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.

Upvotes: 1

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

Upvotes: 0

Related Questions