I just started with DI / Dagger 2. I have a huge project. To try dagger 2, I started with injecting my singleton class 'MyPreferences'. This class handles all app actions from and to the SharedPreferences.
Auto-injecting the SharedPreferences in the MyPreferences went perfectly.
However, I am using this singleton in about 50 classes, I used to do this:
MyPreferences.getInstance(context).getXXXSetting();
I have changed this to dagger2 injection in a few classes, and it works fine, but I find myself copying these lines all the time:
@Inject
protected MyPreferences myPreferences;
protected void initInjection(Context context) {
((RootApplicationDi) context.getApplicationContext()).getComponent().injectTo(this);
}
// + call initInjection @ onCreate / constructor
For such a simple call I need all these lines in about 35-40 (super) classes. Am I missing something? Is this really the way to go?
My previous answer was for Dagger 1 and thus incorrect. Here is example solution for Dagger 2:
In your application class:
In your base
Activity
class which your activities extend:And in your activity you can now have just one line for the injection: