Reputation: 374
I have a class annotated with @Singleton like this:
@Singleton
class SomeClass @Inject constructor() { ... }
and I use it in other classes like this:
class OtherClass {
@Inject
lateinit var someclass: SomeClass
init { DaggerAppComponent.create().inject(this) }
}
@Component
@Singleton
interface AppComponent {
fun inject(otherClass: OtherClass)
}
But I get different instances in every class I inject SomeClass into. What am I doing wrong?
Upvotes: 0
Views: 272
Reputation: 336
By calling DaggerAppComponent.create()
in the OtherClass
init{}
block you always creating a new DaggerAppComponent
with each OtherClass
instance.
You should cache your component in your application scope to make those @Singleton
annotation be effective for you.
I think the Application
class is a good place to do that. You can find a small example here.
Upvotes: 1