Dagger2生成多个实例

时间:2018-05-28 11:49:38

标签: kotlin dagger-2

我在我的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类时它都会给我新的对象。

2 个答案:

答案 0 :(得分:3)

仅当您重复使用相同的组件时,才会考虑@Singleton注释(以及任何其他范围注释)。换句话说,Dagger无法在同一组件的不同实例中尊重您的@Singleton范围。

因此,为了注入相同的MeterCollection实例,您还应该重用相同的DaggerAppComponent实例(例如,将其放在实例变量中)。

答案 1 :(得分:0)

SingletonProvider注释不会使用每次调用方法时创建的对象。我将课程重构为:

@Module(includes = [UtilModule::class])
class MeterCollectionModule {

val myMeterConnection = MeterConnection()

@Singleton
@Provides
fun meterCollection(){
    return myMeterConnection
}

(这与@ user2340612建议的解决方案相同)