匕首2:为单例注入大量访问点

编程入门 行业动态 更新时间:2024-10-18 10:22:22
本文介绍了匕首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:为单例注入大量访问点

本文发布于:2023-10-31 04:33:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545019.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:匕首

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!