Kotlin Dagger2生成多个实例
我在我的kotlin项目和pom文件中使用了Dagge2。我在android项目中使用了Dagger,效果很好。但不知何故,我不明白为什么Dagger会生成我在kotlin中的每个对象的多个实例 下面是我的组件Kotlin Dagger2生成多个实例,kotlin,dagger-2,Kotlin,Dagger 2,我在我的kotlin项目和pom文件中使用了Dagge2。我在android项目中使用了Dagger,效果很好。但不知何故,我不明白为什么Dagger会生成我在kotlin中的每个对象的多个实例 下面是我的组件 @Singleton @Component(modules = [MeterCollectionModule::class]) interface AppComponent { fun meterCollection(): MeterCollection } Dagger
@Singleton
@Component(modules = [MeterCollectionModule::class])
interface AppComponent {
fun meterCollection(): MeterCollection
}
DaggerAppComponent
.builder()
.build()
.inject(this)
这是我的模块
@Module(includes = [UtilModule::class])
class MeterCollectionModule {
@Singleton
@Provides
fun meterCollection() = MeterCollection()
}
这就是我构建应用组件的方式
@Singleton
@Component(modules = [MeterCollectionModule::class])
interface AppComponent {
fun meterCollection(): MeterCollection
}
DaggerAppComponent
.builder()
.build()
.inject(this)
我调试代码,发现每次注入MeterCollection类时,它都会给我一个新对象。只有在重用相同的组件时才会考虑
@Singleton
注释(以及任何其他范围注释)。换句话说,Dagger不能跨同一组件的不同实例尊重您的@Singleton
范围
因此,为了注入相同的
MeterCollection
实例,还应该重用相同的DaggerAppComponent
实例(例如,将其放入实例变量中)。单例和提供程序注释不会处理每次调用方法时创建的对象。我会将类重构为:
@Module(includes = [UtilModule::class])
class MeterCollectionModule {
val myMeterConnection = MeterConnection()
@Singleton
@Provides
fun meterCollection(){
return myMeterConnection
}
(这与@user2340612提出的解决方案相同)您是否重复使用相同的AppComponent
来检索MeterCollection
?如何在不同的类中使用相同的DaggerAppComponent?您有多个选项。例如,您可以将其链接到应用程序特有的应用程序
对象,将其分配到对象
字段,并在需要的地方传递。这是一个很好的观点,但这只有在我在安卓系统中开发应用程序时才有效。但我的问题是,我正在开发一个基于Java的应用程序。这实际上取决于您的用例:如果这些类以某种方式连接起来(例如,如果它们是通过工厂创建的-毕竟我们是在Java中-您可以将组件
保留在工厂中)。如果您需要从任何地方访问组件,请考虑使用单模式或某种“应用程序”对象(程序将有1个入口点,您可以将其视为您的“应用程序”对象)。