如何在Android上使用Kotlin获得Dagger 2模块中的组件依赖关系



我有一个适用于Android上FragmentDagger2 Component。我通过动态注入片段来初始化组件。现在,我需要从片段模块向依赖项提供活动上下文。我假设用Fragment作为参数编写一个提供程序方法会自动获得模块中的Fragment引用,我可以从中提取上下文。但我无法编译代码。

应用程序组件还提供了一个Context,因此我添加了一个限定符来获取活动上下文。我认为这不应该造成任何问题。这是我的代码:

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class FragmentScope
@FragmentScope
@Component(modules = [FragmentModule::class],
dependencies = [AppComponent::class])
interface FragmentComponent {
fun inject(myFragment: MyFragment)
@Component.Builder
interface Builder {
fun appComponent(component: AppComponent): Builder
fun build(): FragmentComponent
}
}
@Module
object FragmentModule {
@Provides
@JvmStatic
@Named("Fragment")
fun provideContext(myFragment: MyFragment): Context = myFragment.context!!
}

编译错误:

[Dagger/MissingBinding] MyFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
public abstract void inject(@org.jetbrains.annotations.NotNull()
^
A binding with matching key exists in component: FragmentComponent

我认为您弄错了FragmentComponentinject方法。这将触发对片段的注射,而不是对组件的片段注射。如果要从片段中获取活动的上下文,则必须在初始化期间将其传递给模块。

@Module
class FragmentModule(val fragment : Fragment) {
@Provides
fun provideContext(): Context = fragment.context!!
}

最新更新