So, what I am trying to accomplish is to ensure that I have only one instance per scope in Dagger2.
Default Singleton scope already works that way. No matter on how many places you inject same object, let's call it GlobalInstance
, method GlobalInstance provideGlobalInstance()
that constructs it will be called once and only once.
On the other side, if I define custom scope, for example @SessionScope
and inside some SessionModule
I make method User provideUser()
, that method (and, consequentially, new User()
constructor) will be called as many times as I am injecting User
. No matter if I use the same module instance every time, User provideUser()
is being called for every @Inject User mUser
I have in my code, resulting with multiple instances, instead of one scope-limited "singleton".
Is there some clear way to achieve it, using regular Dagger api. One way to do it is to have lazy getters inside the module class, but it is not very clean way to do it.
Please note that @Singleton
scope is functionally equivalent to any other custom scope you define.
It means that you could have two flavors of @Provides
methods in SessionModule
:
@Provides @SessionsScope
- provides "session singletons" (more on this later)@Provides
- provides new object on each injectionPlease note that the term "singleton" have some ambiguity when we talk about Dagger, therefore I prefere to use term "scoped objects". When scoped object injected with Dagger for the first time, the component caches its instance and returns it on each subsequent injections PERFORMED BY THE SAME COMPONENT.
For more information you can read this post: Android Dagger 2 Scopes Demistified