在执行dagger-2到hilt迁移时,模块出现此错误
错误:
FooModule.Companion is listed as a module, but it is a companion
object class.
Add @Module to the enclosing class
and reference that instead.
Hilt之前
@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)
}
}
Hilt之后
@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
Dagger 2.26在@Component
或@Subcomponent
的modules
参数中包含伴随对象模块是一个错误。相反,如果包含类是一个模块,则会自动包含伴随对象。Hilt的@InstallIn
只是将带注释的模块添加到生成的组件类中,因此如果使用@InstallIn
对伴随对象进行注释,则会出现同样的错误。
从伴随对象中删除@InstallIn
(和@Module
(,一切都会正常工作。
您需要将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)
}
}