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?
相关问题
- ImportError shows up with py.test, but not when ru
- Can not resolve symbol for dagger component in and
- Injecting test module with dagger2
- Dealing with circular inclusion in a parent/child
- Static provide method in Dagger2
相关文章
- Create Custom Dagger 2 Scope with Kotlin
- What are the advantages of using DispatchingAndroi
- Can not resolve symbol DaggerApplicationComponent
- Dagger 2 - how to create/provide a EagerSingleton
- Dagger2 Inherited subcomponent multibindings
- Forward declarations in C++ modules (MSVC)
- HasActivityInjector can not be resolved in android
- Kotlin dagger 2 Android ViewModel injection error
The easy way out is to use
Lazy<T>
on one side.This is how I resolved it, without parent classes.
Class 1: Engine. (in component interface) @Provides public Engine myEngine(Context context) { return new Engine (context); }
Class 2: Parts. Engine also needs Parts instance but the creation is delayed.
Circular dependency can be achieved but one class must be initiated first before the other.
Again, if possible, refactor code to avoid circular DI.
After an excessive amount of thought and talks with coworkers, we ended up doing the following:
Explaining this -- we moved the actual logic of Foo into a parent class (FooWithoutDep), that took the circular dependency as a settable field rather than a constructor parameter. Then the original class just contained a constructor that took the circular dependency and called the setter. The other class, Bar, depended on the parent (FooWithoutDep), and called the setter explicitly, passing itself (
this
). This enables all the existing references to the class to remain the same, while still using Dagger to inject all the dependencies.This seemed confusing enough to be worth writing up here.