android - 在具有抽象片段的 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)
解决方案
因此,您在Fragment1
这里使用它,而您的模块不知道这一点Fragment1
,因此您需要通过 Fragment 中的 Component 提供此依赖项。
@Provides
internal fun provideFragment1View(fragment: Fragment1): Fragment1Contract.View {
return fragment
}
在你的组件中,你必须这样做:
@BindsInstance
fun view(view: Fragment1): Builder
推荐阅读
- hazelcast - 带有同步备份的嵌入式 Hazelcast 备份读取
- javascript - 提交成功或失败后如何在反应表单中显示 toastr 警报?
- javascript - 使用 node.js + express.js 网站减小字体大小
- sql - presto sql比较不同表的列并过滤掉不匹配的
- vim - Vim 运行的语言是如何工作的?
- swift - 如何使用 Swift 每秒有效地修改 5000 像素的大 UIImage 60 次
- c# - DSharpPlus 如何在 C# 中为 NSFW 创建或设置不和谐频道
- python - 为大量线程类实现线程池
- python - /posts/12/tesing/like/quote_from_bytes() 预期字节处的 TypeError
- ios - Flutter- 无法通过 VSCode 构建 ios,只能通过 Xcode