How do I create a singleton object that I can access anywhere from any place in my code?
- Objects(1) from which I want to inject my signleton component can't be created withing dagger.
- Those objects don't have common dependencies which I can access (like
getApplication()
Quick to an example:
InjectedClass:
public class InjectedClass {
public InjectedClass() {
System.out.println("injected class created");
}
}
HolderClassA:
public class HolderClassA { // this is one of object I marked with (1)
@Inject InjectedClass b;
public HolderClassA() {
Injector build = DaggerInjector.builder().build();
build.inject(this);
System.out.println(b);
}
}
HolderClassB:
public class HolderClassB { // this is another object I marked with (1)
@Inject InjectedClass b;
public HolderClassB() {
Injector build = DaggerInjector.builder().build();
build.inject(this);
System.out.println(b);
}
}
Provider:
@Module
public class Provider {
@Provides
@Singleton
InjectedClass provideInjectedClass() {
return new InjectedClass();
}
}
Injector:
@Component(modules = {Provider.class})
@Singleton
public interface Injector {
void inject(HolderClassA a);
void inject(HolderClassB a);
}
Somewhere in code:
new HolderClassA();
Somewhere else in code that is NO WAY related to previous code, nor has the same parent or can access same objects (like in dagger guide with getApplication()
):
new HolderClassB();
Actual result: two instances of InjectedClass are crated
Expected result: a single instance of InjectedClass
is created.
The issue is DaggerInjector.builder().build();
creates different scopes which don't know about each other. For example, I can solve this issue by creating static variable DaggerInjector.builder().build()
and call inject from it. But thus it wouldn't be dependency injection anymore, but rather not trivial singleton pattern.