我刚开始使用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:为单例注入大量访问点
发布评论