Dagger 2: injecting singleton with lots of access

2019-09-05 05:55发布

问题:

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?

回答1:

My previous answer was for Dagger 1 and thus incorrect. Here is example solution for Dagger 2:

In your application class:

private MyDagger2Component mDependencyInjector;


@Override
public void onCreate() {
    super.onCreate();

    mDependencyInjector = DaggerMyDagger2Component.builder()...build();
}


public MyDagger2Component getDependencyInjector() {
    return mDependencyInjector;
}

In your base Activity class which your activities extend:

protected MyDaggerComponent getDependencyInjector() {
    return ((MyApplication) getApplication()).getDependencyInjector();
}

And in your activity you can now have just one line for the injection:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getDependencyInjector().inject(this);
    ...
}