使用DI进行课堂注射有什么意义吗 [英] Is there any point in using DI for class injections

查看:47
本文介绍了使用DI进行课堂注射有什么意义吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angular1中,我们经常使用factory来注入类,而不是实例.在angular2中,我可以这样做:

In angular1 we often used factory to inject classes, not instances. In angular2, I can do the same:

{provide: MyClass, useFactory: () => { return MyClass }}

...
constructor(MyClass) {
   let instance = new MyClass();
}

但是,我记得读过这篇文章,因为缺少JS模块是有道理的.现在我们使用ES6模块,我想知道是否有必要在类注入中使用DI?我看到许多不使用角度DI来获取类,而是通过 import 语句访问它们的库.

However, I remember reading that this was justified by the absence of JS modules. Now that we use ES6 modules, I'm wondering if there is any need to use DI for class injections? I see many libraries that don't use angular DI to get classes, but access them through import statements.

推荐答案

{provide: MyClass, useFactory: () => { return MyClass }}

{provide: MyClass, useValue: MyClass }

本质上是同一件事.是的,对于应该手动实例化的类使用DI是有意义的.

are essentially the same thing. Yes, it makes sense to use DI for the classes that are supposed to be instantiated manually.

在JS中执行DI时不会产生任何问题(ES.Next):

It creates no problems when DI is performed in JS (ES.Next):

constructor(@Inject(MyClass) MyClass) {
  this.MyClass = new MyClass;
}

但是在TypeScript中使用它可能不太方便,因为应该正确指定类型:

But it may be less convenient to use in TypeScript because the types should be properly specified:

constructor(@Inject(MyClass) MyClass: typeof MyClass) {
  this.MyClass = new MyClass;
}

将其作为提供程序可以在不修补原始代码的情况下随时替换或增强功能,这对于第三方库来说是一个很好的特征.

Having it as a provider allows to replace or augment the functionality any time without patching the original code, which is a good trait for third-party libraries.

它提供了更好的可测试性, MyClass 可以用存根类或间谍函数代替.当不涉及DI时,这会使测试变得更加复杂,并且需要在导入级别上实现DI,例如使用 rewire-webpack .

And it offers better testability, MyClass can be replaced with a stub class or spy function. When no DI is involved, this makes testing more complicated and requires to implement DI on import level, e.g. with rewire-webpack.

这篇关于使用DI进行课堂注射有什么意义吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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