Dagger 2: injecting singleton with lots of access points

大憨熊 提交于 2019-12-11 14:29:43

问题


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);
    ...
}


来源:https://stackoverflow.com/questions/33544922/dagger-2-injecting-singleton-with-lots-of-access-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!