I have a Dagger object graph that is able to produce instances of MyClass
implicitly, as the constructor of MyClass
is annotated with @Inject
.
I also have a module that I plus
onto my existing graph. My goal is for the plus'ed graph, and only for the plus'ed graph, to treat MyClass
as a singleton and to always return the same instance.
How can I best achieve that with minimal boilerplate code, i.e. without
a) Constructing the instances myself in the plus'ed-on module by writing a @Provides @Singleton
method, declaring all the dependencies of MyClass
:
@Module public class Submodule {
@Provides @Singleton MyClass provideMyClass(DepA depA, DepB depB) {
return new MyClass(depA, depB);
}
}
b) Extracting an interface from MyClass
and again writing provider methods:
@Module public class Submodule {
@Provides @Singleton IMyClass provideMyClass(MyClassImpl myClass) {
return myClass;
}
}
My concrete use case is that of an Android app, where an Activity
instance depends on a presenter that should also be injected in fragments of the activity. Because several instances of the same Activity
can exist, I can't declare MyClass
a singleton globally.
I guess in the end, the question boils down to how one can write something like this, without the dependency cycle:
@Provides @Singleton public MyClass provideMyClass(MyClass m) { return m; }