I'm trying to create an Android library alongside another project whilst learning DI with Dagger 2. It's proving to be more difficult than expected.
My Question
I'm trying to use a singleton class called MySingleton that I want to access from both my Android library as well as the main application.
Current Setup
Basically I have a singleton class called MySingleton in my Android library project. In the project I have a class called SingletonModule which is a Dagger2 module that provides my singleton like so.
@Provides @Singleton
MySingleton providesMySingleton() {
return new MySingleton();
}
Ok, now in my actual application in I have the following component.
@Singleton
@Component(modules = {SingletonModule.class})
public interface ApplicationComponent {
void inject( MyApplication application );
}
So this is used to inject MySingleton into the MyApplication class. It does it like so.
this.applicationComponent = DaggerApplicationComponent.builder()
.singletonModule( new SingletonModule() ) // does it for you as empty constructor
.build();
applicationComponent.inject(this);
This is great and the instance of MySingleton that I'm injecting by field is working fine.
What I have Tried
In my Android library project I created a new component called SingletonComponent which did the same as ApplicationComponent, just provided the MySingleton object. Then in the MyService class which extends Service I injected, by field, the MySingleton object. This did not have the effect I was after. It did object a MySingleton object but it was not the same instance as created when injecting into my actual application. I believe this is because it is a new component that I'm creating...
What am I doing wrong here?
I have looked on many different sites and followed many tutorials but something just isn't clicking with this dependency injection.