Search code examples
javaandroiddagger-2circular-dependencydagger

How to resolve a circular dependency while still using Dagger2?


I have two classes, Foo<T> and Bar, which depend on each other, as well as various other classes. I am using Dagger-2 for dependency injection, but if I naively add the circular dependency, Dagger hits a stack overflow at runtime. What's a good way to refactor the classes to fix this, while still using Dagger to inject all the other dependencies, and with minimal duplication and changes to existing calls?


Solution

  • The easy way out is to use Lazy<T> on one side.

    Lazy<Foo> foo;
    
    @Inject
    Bar(Lazy<Foo> foo) {
        this.foo = foo;
    }
    
    // use foo.get(); when needed