Android中的Dagger 2和组件依赖

时间:2018-06-17 22:16:16

标签: android kotlin dagger-2

活动

@PerActivity
@Component(modules = [ActivityModule::class])
interface ActivityComponent

应用

@Singleton
@Component(modules = [
    HttpModule::class,
    ApplicationModule::class
])
interface AppComponent

特定活动

@Component(
        modules = [LandingModule::class],
        dependencies = [AppComponent::class, ActivityComponent::class]
)
@ActivityContext
interface LandingComponent {
    fun inject(activity: MainActivity)
}

应用

   override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        DaggerLandingComponent.builder().build().inject(this)
   }

我得到的错误是AppComponent有一个单例范围 cannot depend on scoped components:

在这种情况下,什么是正确的解决方案?

1 个答案:

答案 0 :(得分:1)

解决此问题的一种常用方法是向您的父组件添加plus方法。因此,ActivityComponent从技术上讲是AppComponent + ActivityComponent,而LandingComponentAppComponent + ActivityComponent + LandingComponent

@Singleton
@Component(modules = [
    HttpModule::class,
    ApplicationModule::class
])
interface AppComponent {
    ActivityComponent plus(module: ActivityModule)
}

@PerActivity
@Subcomponent(modules = [ActivityModule::class])
interface ActivityComponent {
    LandingComponent plus(module: LandingModule)
}

@ActivityContext
@Subcomponent(modules = [LandingModule::class])
interface LandingComponent {
    fun inject(activity: MainActivity)
}

应用

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    AppComponent.builder().build().plus(ActivityModule()).plus(LandingModule())
}