I have singleton class that 2 other classes depend on: another singleton and a service. The problem is that in practice each of them receives a different instance of what's supposed to be a singleton. I'm trying to figure out why. Here's the gist of it:
The singleton dependency class:
@Singleton
public class SingletonDependency {
@Inject
public SingletonDependency() {
// ...
}
}
The other singleton which depends on it:
@Singleton
public class DependentClass {
@Inject
public DependentClass(SingletonDependency singletonDependency) {
// ...
}
}
The service which depends on it:
public class DependentService extends Service {
@Inject SingletonDependency mSingletonDependency;
@Override
public void onCreate() {
CoreInjector.INSTANCE.getCoreComponent().inject(this);
}
}
I do not provide SingletonDependency
explicitly since it has a @Inject
constructor and Dagger2 takes care of it for me. Is this the root of it?
Here's my injector:
public enum CoreInjector {
INSTANCE;
private CoreComponent mCoreComponent;
public void init(Context context) { // called by the Application's onCreate()
mCoreComponent = DaggerCoreComponent.builder()
.coreModule(new CoreModule(context))
.build();
}
public CoreComponent getCoreComponent() {
return mCoreComponent;
}
}
The Component itself:
@Singleton
@Component(modules = {CoreModule.class})
public interface CoreComponent {
void inject(DependentService dependentService);
}
The Module itself doesn't provide the dependency explicitly, but once I do, everything works as expected - same instance.
Conclusions posted as an answer.
I figured it out. My singleton class implements an interface, which is what my dependent classes depends on - not the implementation. I guess Dagger2 can't make that leap even though the implementation has a injected constructor.
Explicit @Provides
method in a module was the only way to go.