繁体   English   中英

Dagger2 - 多模块 - 组件中存在具有匹配键的绑定

[英]Dagger2 - Multi Module - A binding with matching key exists in component

背景

我正在尝试在多模块设置中使用匕首。 我的目标之一是减少使用的组件数量。 所以基本上针对每个功能模块 1 个组件。

设置核心->应用程序->功能

问题

Dagger 失败,出现异常A binding with matching key exists in component:这是指I have bound a dependency somewhere in my entire object graph but it cannot be reached.

但是对于我的场景,我在我的活动中创建子组件并调用注入以确保该组件可以访问我的活动。 至少在我的理解中应该可以访问,但它仍然无法提供我的视图模型的依赖关系。

这是示例/多模块,以防有人想尝试。

堆栈跟踪

/Users/feature1/build/**/FeatureComponent.java:8: error: [Dagger/MissingBinding]
com.**.FeatureActivity cannot be provided without an @Inject constructor or an @Provides-annotated 
method. This type supports members injection but cannot be implicitly provided.
public abstract interface FeatureComponent {
                ^
  A binding with matching key exists in component: com.**.FeatureComponent
      com.**.FeatureActivity is injected at
          com.**.FeatureModule.provideVM(activity)
      com.**.FeatureViewModel is injected at
          com.**.FeatureActivity.vm
      com.**.FeatureActivity is injected at
          com.**.FeatureComponent.inject(com.**.FeatureActivity)

应用组件

@AppScope
@Component(dependencies = [CoreComponent::class])
interface AppComponent {

    fun inject(app: MainApp)

    @Component.Factory
    interface Factory {
        fun create(
            coreComponent: CoreComponent
        ): AppComponent
    }
}

核心组件

@Singleton
@Component
interface CoreComponent {

    fun providerContext(): Context

    @Component.Factory
    interface Factory {
        fun create(
            @BindsInstance applicationContext: Context
        ): CoreComponent
    }
}

特征组件

@Component(
    modules = [FeatureModule::class],
    dependencies = [CoreComponent::class]
)
@FeatureScope
interface FeatureComponent {

    // Planning to use this component as a target dependency for the module.
    fun inject(activity: FeatureActivity)
}

功能模块

@Module
class FeatureModule {

    @Provides
    fun provideVM(activity: FeatureActivity): FeatureViewModel {
        val vm by activity.scopedComponent {
            FeatureViewModel()
        }
        return vm
    }
}

功能虚拟机

class FeatureViewModel @Inject constructor(): ViewModel() 

由于我使用activity来提供我的视图@BindsInstance viewModel绑定我想要注入的任何活动或片段的实例。

简而言之,如果我将我的功能组件更改为以下代码,它就会开始工作,我在创建组件时绑定活动的实例。

PS:如果有人知道仅使用一个组件可以更好地在后期注入片段,请随时改进此答案。

特征组件

@Component(
    modules = [FeatureModule::class],
    dependencies = [CoreComponent::class]
)
@FeatureScope
interface FeatureComponent {

    fun inject(activity: FeatureActivity)

    @Component.Factory
    interface Factory {
        fun create(
            @BindsInstance applicationContext: FeatureActivity,
            coreComponent: CoreComponent,
        ): FeatureComponent
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM