将 Hilt @IntallIn 用于具有静态提供方法的 dagger-2 模块
Using Hilt @IntallIn for a dagger-2 module which has static provides method
在执行 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
Dagger 2.26 使在 @Component
或 @Subcomponent
的 modules
参数中包含伴随对象模块成为错误。相反,如果包含 class 是一个模块,则会自动包含伴随对象。 Hilt 的 @InstallIn
只是将带注释的模块添加到生成的组件 class,因此如果您使用 @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)
}
}
在执行 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
Dagger 2.26 使在 @Component
或 @Subcomponent
的 modules
参数中包含伴随对象模块成为错误。相反,如果包含 class 是一个模块,则会自动包含伴随对象。 Hilt 的 @InstallIn
只是将带注释的模块添加到生成的组件 class,因此如果您使用 @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)
}
}