首页 > 解决方案 > 在具有抽象片段的 MVP 架构中,如果没有 @Provides-annotated 方法,则无法提供片段

问题描述

我知道关于这个主题有很多问题,但我已经浏览了所有这些问题并尝试了一整天,但我仍然没有找到解决问题的方法。我对匕首很陌生,但我正在从事的项目正在使用它,并且在我们遇到这种情况之前它运行良好:

我们有一个注入提供程序的抽象片段(在 MVP 架构中)和 3 个扩展该片段的片段(其中没有其他注入)。

我有以下代码:

abstract class Fragment1: DaggerFragment(), Fragment1Contract.View {

    //region Properties
    @Inject
    lateinit var presenterFragment1Contract: Fragment1Contract.Presenter<Fragment1Contract.View>

以及扩展此片段的 3 个片段,没有太多代码(我尝试在这些片段的 onAttach 方法中添加 AndroidSupportInjection.inject(this) 但这没有帮助)。

我有这个模块:

@Module
open class Fragment1Module {
   @Provides
   internal fun provideFragment1View(fragment: Fragment1): Fragment1Contract.View {
       return fragment
   }

   @Provides
   internal fun provideFragment1Presenter(view: Fragment1Contract.View):   Fragment1Contract.Presenter<Fragment1Contract.View> {
       return Fragment1Presenter(view)
   }
}

和这个 :

@Module
abstract class ActivityBindingModule {
    @PerActivity
    @ContributesAndroidInjector(modules = arrayOf(Fragment1Module::class))
    abstract fun bindFragment1(): Fragment1

    @PerActivity
    @ContributesAndroidInjector(modules = arrayOf(Fragment1Module::class))
    abstract fun bindFragment2(): Fragment2

    @PerActivity
    @ContributesAndroidInjector(modules = arrayOf(Fragment1Module::class))
    abstract fun bindFragment3(): Fragment3

    @PerActivity
    @ContributesAndroidInjector(modules = arrayOf(Fragment1Module::class))
    abstract fun bindFragment4(): Fragment4
}

最后是这个组件:

@PerApplication
@Component(modules = [ActivityBindingModule::class, AndroidSupportInjectionModule::class, Fragment1Module::class])

interface ApplicationComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: Application): Builder

        fun build(): ApplicationComponent
    }

    fun inject(app: MyApplication)
}

我尝试了不同的方法,但出现以下错误:

如果没有 @Provides-annotated 方法,就无法提供 Fragment1

我尝试添加不同的@Provides 方法,但我最终会遇到循环问题,或者缺少 Fragment2、3 和 4 或 Fragment1Contract.View 的注入

我不知道我错过了什么,但此时任何帮助都会很有用!

更新 :

我尝试添加:

    @BindsInstance
    fun view(view: Fragment1): Builder

但现在我有以下错误:

Fragment1 is bound multiple times 
@BindsInstance void dagger.android.AndroidInjector.Builder.seedInstance(T)> @org.jetbrains.annotations.NotNull @BindsInstance androidapp.injection.ApplicationComponent.Builder
injection.ApplicationComponent.Builder.view(Fragment1)

标签: androidkotlindagger-2

解决方案


因此,您在Fragment1这里使用它,而您的模块不知道这一点Fragment1,因此您需要通过 Fragment 中的 Component 提供此依赖项。

@Provides
internal fun provideFragment1View(fragment: Fragment1): Fragment1Contract.View {
       return fragment
   }

在你的组件中,你必须这样做:

  @BindsInstance
  fun view(view: Fragment1): Builder

推荐阅读