简体   繁体   中英

error: [Dagger/DependencyCycle] Found a dependency cycle with Dagger2

I am trying to use @BindsInstance in a Component Builder, but can't inject dependency into a module

That is the component:

@Component(modules = [MainModule::class])
interface MainComponent {
    fun inject(activity: MainActivity)

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun mainDep(dep: MainTest): Builder

        fun build(): MainComponent
    }
}

That is the module:

@Module
class MainModule {

    @Provides
    fun provideMainTest(mainTest: MainTest) = mainTest
}

That is the class to inject:

interface MainTest {
    fun mainTest()
}

class MainTestImpl: MainTest {
    override fun mainTest() {
        println("main test")
    }
}

But when I try to inject it into MainActivity I get a compiler error

error: [Dagger/DependencyCycle] Found a dependency cycle:
public abstract interface MainComponent {
                ^
      com.example.testdagger.di.MainTest is injected at
          com.example.testdagger.di.MainModule.provideMainTest(mainTest)
      com.example.testdagger.di.MainTest is injected at
          com.example.testdagger.di.MainModule.provideMainTest(mainTest)

Can you try and say what will happen like this:

    @BindsInstance
    fun mainDep(dep: MainTestImpl): Builder

and also:

@Module
class MainModule {

    @Provides
    fun provideMainTest(mainTestImpl: MainTestImpl): MainTest = mainTestImpl
}

I know that it is not exactly what you want to achieve, but I want to check the result. Also, please provide how you create the component and how do you inject the Activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM