is it possible to use Dagger 2.0 Constructor injection and singleton at one time. I don't find the answer in the documentation.
Example:
@Singleton
public class MyClass {
private final OtherClass member;
@Inject
public MyClass(OtherClass member){
this.member = member;
}
}
Constructor injection does work for sure. But is it guaranteed that MyClass is created as a singleton if I write @Singleton on the class?
Thank you
Yes.
Since Dagger 2 generates the source code for you, it is easy to inspect what is happening. For example, when using the following module in combination with your
MyClass
:The following implementation is generated:
In
initialize(Builder)
, you can see that aScopedProvider
is used as aProvider
forMyClass
. When calling themyClass()
method, theScopedProvider
'sget()
method is called, which is implemented as a singleton: