【问题标题】:Dagger with Hilt inject ActivityContext in adapter from module带有 Hilt 的 Dagger 从模块中的适配器中注入 ActivityContext
【发布时间】:2020-07-11 15:04:12
【问题描述】:

我正在使用 dagger 和 hilt,我想将 @ActivityContext 从一个模块注入到一个适配器,但是我收到了这个错误 -

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1/mnt/My Projects/app/build/generated/source/kapt/debug/app/myapp/MyApp_HiltComponents.java:156: error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ActivityContext android.content.Context cannot be provided without an @Provides-annotated method.
  public abstract static class ApplicationC implements MyApp_GeneratedInjector,
                         ^
      @dagger.hilt.android.qualifiers.ActivityContext android.content.Context is injected at
          app.myapp.di.modules.activitiesModules.HomeActivityModule.provideAdapterFragmentState(context)
      app.myapp.ui.base.AdapterFragmentState is injected at
          app.myapp.ui.home.HomeActivity.adapterFragmentState
      app.myapp.ui.home.HomeActivity is injected at

这是我的 HomeActivityModule -

@Module
@InstallIn(ActivityRetainedComponent::class)
object HomeActivityModule {

    @Provides
    @ActivityRetainedScoped
    fun provideAdapterFragmentState(@ActivityContext context: Context): AdapterFragmentState {
        return AdapterFragmentState(context)
    }

}

这是我的适配器 -

@ActivityRetainedScoped
class AdapterFragmentState @Inject constructor(@ActivityContext context: Context)
    : FragmentStateAdapter(context as AppCompatActivity){

哪一部分错了?

【问题讨论】:

    标签: android kotlin dagger dagger-hilt


    【解决方案1】:
    @Module
    @InstallIn(ActivityComponent::class)
    object HomeActivityModule {
    
        @Provides
        @ActivityScoped
        fun provideAdapterFragmentState(@ActivityContext context: Context): AdapterFragmentState {
            return AdapterFragmentState(context)
        }
    
    }
    

    已编辑:

    因为 ActivityRetainedComponent 存在于配置更改中,而 ActivityComponent 不存在。

    如果你想注入@ActivityContext,你的模块应该安装在ActivityComponent中,并且注入的对象必须是@ActivityScoped。

    【讨论】:

    • 一个相关主题@SaeedLotfi...您在dagger-hilt 标签中有足够的声誉来支持同义词。你可以在这里做吗:stackoverflow.com/tags/dagger-hilt/synonyms?似乎没有版主关心给hilt相关标签带来秩序,所以我正在尝试自己协调。
    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多