Android Dagger Dependency Cycle
Solution 1:
Your problem: AClass has a constructor dependency on BClass, which has a constructor dependency on AClass. Even without Dagger, this wouldn't work: If they depend on each other, which would you create first?
Your attempted solution: If you create one of your classes (BClass) using new
, and it no longer has an @Inject
-annotated constructor, you could wait until after AClass is constructed to populate your BClass instance. However, if you create an object using new
, you'll need to inject it by passing it into a members-injection method or MembersInjector<BClass>
object. You'll also need to make sure that this happens outside of the @Provides
method (because the whole reason @Provides
is being called is so you can construct a value to pass into AClass's constructor). This is fragile and fairly ugly.
My suggestion: Use indirection via Provider. Have AClass inject Provider<BClass>
, or BClass inject Provider<AClass>
, or both. As long as you don't call get
within the constructor, you'll allow Dagger to create AClass and defer the creation of BClass until you need it. You need no additional configuration in order to inject a Provider<T>
or Lazy<T>
for any class T you've bound in your Component; see "Bindings in the Graph" in the User's Guide for the full list of available injections.
Solution 2:
I made this possible using dagger.Lazy and Hilt (almost same as dagger - it is using dagger under the hood). But be careful. Circular dependency may be result of bad design and can lead to many problems. Here is example:
classCls1@Injectconstructor() {
@Injectlateinitvar cls2: dagger.Lazy<Cls2>
}
classCls2@Injectconstructor() {
@Injectlateinitvar cls1: dagger.Lazy<Cls1>
}
@HiltAndroidAppclassApplicationClass: Application() {
@Injectlateinitvar cls1: Cls1
@Injectlateinitvar cls2: Cls2
overridefunonCreate() {
super.onCreate()
}
}
Post a Comment for "Android Dagger Dependency Cycle"