Search code examples
androiddependency-injectiondagger-2dagger

Dagger 2 - Why am I getting circular reference error?


I have an already working dagger implementation. My android Application class is the one which inits Dagger2 implementation.

However when I add a method that uses Activity argument, then I get the dagger error:

error: [ComponentProcessor:MiscError] dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.

I have tested different variations and it only throws the error when I use the Activity param:

class MyApplication: Application() {

    ...

    fun addingThisFunWorks()

    fun addingThisFunReturningSomethingWorks(): ReturnClass

    fun addingThisFunWithParameterWorks(value: Int)

    fun addingThisFunThrowsDaggerError(activity: Activity)

}

Is it because Activity class depends on the Application class and that becomes circular somehow?


Solution

  • The problem is that Activity and Fragment references inside this class somehow is interpreted as a circular reference.

    To fix it I need to create an "Intermediate" manager which has the function I need.

    for example:

    class MyApplication: Application() {
    
        ...
    
        fun addingThisFunWorks()
    
        fun addingThisFunReturningSomethingWorks(): ReturnClass
    
        fun addingThisFunWithParameterWorks(value: Int)
    
        fun returnMyManager(): MyManager
    
    }
    

    And have:

    class MyManager {
        fun addingThisFunThrowsDaggerError(activity: Activity)
    }