Ahsan Saeed
Ahsan Saeed

Reputation: 741

Dagger2 generate multiple instances

I'm using Dagge2 in my kotlin project with pom file. I worked with Dagger in my android projects and it worked fine. But somehow I don't understand why Dagger generating multiple instances of my every object in kotlin.

Below is my Component

@Singleton
@Component(modules = [MeterCollectionModule::class])
interface AppComponent {    

fun meterCollection(): MeterCollection

}

And this is my Module

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

@Singleton
@Provides
fun meterCollection() = MeterCollection()
}

That's how I'm building my AppComponent

 DaggerAppComponent
      .builder()
      .build()
      .inject(this)

I debug my code and see, every time I inject MeterCollection class it gives me new object.

Upvotes: 2

Views: 1174

Answers (2)

Anton
Anton

Reputation: 1419

Singleton and Provider annotations won't work with object which is created every time method is called. I'd refactor the class to:

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

val myMeterConnection = MeterConnection()

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

(which is identical solution to what @user2340612 proposed)

Upvotes: 1

user2340612
user2340612

Reputation: 10713

The @Singleton annotation (as well as any other scope annotation) is taken into account only if you're reusing the same component. In other words, Dagger is not able to respect your @Singleton scope across different instances of the same component.

Hence, in order to inject the same MeterCollection instance, you should also reuse the same DaggerAppComponent instance (e.g., by putting it in an instance variable).

Upvotes: 3

Related Questions