【问题标题】:Using Hilt @IntallIn for a dagger-2 module which has static provides method将 Hilt @IntallIn 用于具有静态提供方法的 dagger-2 模块
【发布时间】:2020-11-06 16:34:10
【问题描述】:

在执行 dagger-2 以阻止迁移时,模块出现此错误

错误:

FooModule.Companion is listed as a module, but it is a companion
object class. 
Add @Module to the enclosing class 
and reference that instead.

刀柄之前

@Module
abstract class FooModule {

 @Binds
 @FooScope
 abstract fun bindsManager(impl: FooManagerImpl): FooManager
 
 @Module
 companion object {
     
   @Provides
   @FooScope 
   @JvmStatic
   fun providesConfig(prefs: SharedPreferences): FooConfig = FooConfigImpl(prefs) 
 }

}

剑柄之后

@InstallIn(ApplicationComponent::class)
@Module
abstract class FooModule {

 @Binds
 @FooScope
 abstract fun bindsManager(impl: FooManagerImpl): FooManager
 
 @InstallIn(ApplicationComponent::class)
 @Module
 companion object {
     
   @Provides
   @FooScope 
   @JvmStatic
   fun providesConfig(prefs: SharedPreferences): FooConfig = FooConfigImpl(prefs) 
 }

}

迁移文档参考:https://developer.android.com/codelabs/android-dagger-to-hilt#4

【问题讨论】:

标签: android kotlin dagger-2 dagger-hilt


【解决方案1】:

Dagger 2.26@Component@Subcomponentmodules 参数中包含伴随对象模块是错误的。相反,如果包含类是模块,则会自动包含伴随对象。 Hilt 的@InstallIn 只是将带注释的模块添加到生成的组件类中,因此如果使用@InstallIn 注释伴随对象,则会出现相同的错误。

从伴随对象中删除@InstallIn(和@Module),一切正常。

【讨论】:

    【解决方案2】:

    你需要把companion object改成object

    @InstallIn(ApplicationComponent::class)
    @Module
    abstract class FooModule {
    
     @Binds
     @FooScope
     abstract fun bindsManager(impl: FooManagerImpl): FooManager
     
     @InstallIn(ApplicationComponent::class)
     @Module
     object AppModule{
         
       @Provides
       @FooScope 
       fun providesConfig(prefs: SharedPreferences): FooConfig = FooConfigImpl(prefs) 
     }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 1970-01-01
      • 2020-11-09
      • 1970-01-01
      • 2022-01-04
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多