匕首2:为单例注入大量访问点 [英] Dagger 2: injecting singleton with lots of access points

查看:66
本文介绍了匕首2:为单例注入大量访问点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用DI / Dagger2。我有一个很大的项目。要尝试使用匕首2,我首先注入了我的单例类 MyPreferences。此类可处理往返于SharedPreferences的所有应用程序操作。

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.

在MyPreferences中自动注入SharedPreferences非常完美。

Auto-injecting the SharedPreferences in the MyPreferences went perfectly.

但是,我在大约50个类中使用此单例,我曾经这样做:

However, I am using this singleton in about 50 classes, I used to do this:

 MyPreferences.getInstance(context).getXXXSetting();

我在几节课中将其更改为dagger2注入,效果很好,但我发现自己始终复制以下行:

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

对于这样一个简单的电话,我需要大约35-40(超级)类中的所有这些行。我想念什么吗?

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?

推荐答案

我以前的答案是针对Dagger 1的,因此是不正确的。这是Dagger 2的示例解决方案:

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

在您的应用程序类中:

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

在您的活动中,现在仅可以进行一行注射: / p>

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

这篇关于匕首2:为单例注入大量访问点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆