与活动相关的依赖关系的问题:获取Dagger / MissingBinding

时间:2019-08-05 12:29:08

标签: kotlin dagger-2

我得到带有以下代码的MissingBinding:

class AnActivityComponent @Inject constructor(activity: Activity)

@Module
abstract class MainActivityModule {
    @ContributesAndroidInjector
    abstract fun contributeAndroidInjector(): MainActivity

    @Binds
    abstract fun bindActivity(mainActivity: MainActivity): Activity
}

@Module
abstract class AppModule(app: App) {
    @Binds
    abstract fun bindApplication(app: App): Application
}

@Component(modules = [AppModule::class, AndroidInjectionModule::class, MainActivityModule::class])
interface AppComponent : AndroidInjector<App> {
}

但是,如果我更改

class AnActivityComponent @Inject constructor(activity: Activity)

class AnActivityComponent @Inject constructor(activity: MainActivity)

它工作正常。我在活动模块中绑定了活动,那又是什么问题?

1 个答案:

答案 0 :(得分:0)

好吧,事实证明@ContributesAndroidInjector不包含在查找中声明的模块,因此您必须更好地组织代码:

class AnActivityComponent @Inject constructor(activity: Activity)

@Module
abstract class ActivitiesModule {
    @ContributesAndroidInjector(modules = [MainActivityModule::class])
    abstract fun contributeAndroidInjector(): MainActivity
}

@Module
abstract class MainActivityModule {
    @Binds
    abstract fun bindActivity(mainActivity: MainActivity): Activity
}

@Module
abstract class AppModule(app: App) {
    @Binds
    abstract fun bindApplication(app: App): Application
}

@Component(modules = [AppModule::class, AndroidInjectionModule::class, ActivitiesModule::class])
interface AppComponent : AndroidInjector<App> {
}