我在我的kotlin项目中使用Dagge2和pom文件。我在我的android项目中与Dagger合作,它运行良好。但不知怎的,我不明白为什么Dagger在kotlin中生成我的每个对象的多个实例。
以下是我的组件
@Singleton
@Component(modules = [MeterCollectionModule::class])
interface AppComponent {
fun meterCollection(): MeterCollection
}
这是我的模块
@Module(includes = [UtilModule::class])
class MeterCollectionModule {
@Singleton
@Provides
fun meterCollection() = MeterCollection()
}
我是如何构建 AppComponent
的 DaggerAppComponent
.builder()
.build()
.inject(this)
我调试我的代码并看到,每次我注入MeterCollection类时它都会给我新的对象。
答案 0 :(得分:3)
仅当您重复使用相同的组件时,才会考虑@Singleton
注释(以及任何其他范围注释)。换句话说,Dagger无法在同一组件的不同实例中尊重您的@Singleton
范围。
因此,为了注入相同的MeterCollection
实例,您还应该重用相同的DaggerAppComponent
实例(例如,将其放在实例变量中)。
答案 1 :(得分:0)
Singleton
和Provider
注释不会使用每次调用方法时创建的对象。我将课程重构为:
@Module(includes = [UtilModule::class])
class MeterCollectionModule {
val myMeterConnection = MeterConnection()
@Singleton
@Provides
fun meterCollection(){
return myMeterConnection
}
(这与@ user2340612建议的解决方案相同)