活动
@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:
在这种情况下,什么是正确的解决方案?
答案 0 :(得分:1)
解决此问题的一种常用方法是向您的父组件添加plus
方法。因此,ActivityComponent
从技术上讲是AppComponent
+ ActivityComponent
,而LandingComponent
是AppComponent
+ 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())
}