我在使用Dagger2将“子”片段划分为另一个Fragment的模块时遇到麻烦。
示例代码:
@Module
abstract class SampleParentModule {
@FragmentScoped
@ContributesAndroidInjector(modules = [SampleChildModule::class])
abstract fun contributeParentFragment(): ParentFragment
}
@Module
abstract class SampleChildModule {
@ChildFragmentScoped
@ContributesAndroidInjector
abstract fun contributeChildFragment(): ChildFragment
}
一切编译正常,然后在运行时我得到:
java.lang.IllegalArgumentException:没有为类<\ ChildFragment>
绑定的注射器工厂
这是我的FragmentScoped
和ChildFragmentScoped
注释。
@Scope
@Retention(AnnotationRetention.RUNTIME)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FILE,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
annotation class FragmentScoped
@Scope
@Retention(AnnotationRetention.RUNTIME)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FILE,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
annotation class ChildFragmentScoped
如果我将ChildFragmentScoped
中的SampleChildModule
注释替换为FragmentScoped
,则将SampleChildModule
添加到SampleParentModule
中,如下所示:@Module(includes = [SampleChildModule::class])
作品。但这不是我想要做的,我只希望子模块可用于一个片段。
SampleParentModule
在ActivityBindingModule
中用于活动,例如:
@Module
abstract class ActivityBindingModule {
@ActivityScoped
@ContributesAndroidInjector(modules = [SampleParentModule::class])
abstract fun sampleActivity(): SampleActivity
}
然后将其添加到主modules
的{{1}}数组中。
这些片段扩展了AppComponent
,而活动扩展了DaggerFragment
。