Search code examples
javadependency-injectiondagger-2

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

Solution

  • 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.