The idea of Inversion Of Control, aka dependency injection is that a class hands over control (read: responsibility) for instantiating dependent instances that the class needs to the container that will provide them with these instances instead.
(控制反转(也称为依赖注入)的思想是,一个类将控制权(读取:责任)移交给实例化,该实例需要将该类实例化到将为其提供这些实例的容器。)
So you would not do something like:
(因此,您将不会执行以下操作:)
public constructor() {
this._katana = new Katana();
this._shuriken = new Shuriken();
}
I am not going to give a full example, because I would basically be copy-pasting the code that they clearly share on their website in the section 'The Basics'.
(我将不举一个完整的例子,因为我基本上将复制粘贴他们在其“基础知识”部分中明确分享的代码。)
They give an example of constructor injection:
(他们给出了构造函数注入的示例:)
public constructor(
@inject(TYPES.Weapon) katana: Weapon,
@inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
) {
this._katana = katana;
this._shuriken = shuriken;
}
This is specifically useful for:
(这特别适用于:)
- Testing, since the dependent object can be mocked and injected
(测试,因为依赖对象可以被模拟和注入)
- Injecting dependent objects based on variable parameters.
(基于可变参数注入依赖对象。)
For example, depending on environment you may want to inject a different configuration object with different values.
(例如,根据环境,您可能需要注入具有不同值的不同配置对象。)
This is just one example. (这只是一个例子。)
Constructor injection is usually preferred over property injection, as the library also seems to support this.
(与属性注入相比,通常首选构造方法注入,因为该库似乎也支持这一点。)
Note that what is injected is an interface, not a concrete class type.
(请注意,注入的是接口,而不是具体的类类型。)
So the class just declares that it needs an object of type Weapon / ThrowableWeapon.
(因此,该类仅声明需要一个Weapon / ThrowableWeapon类型的对象。)
The concrete binding happens in inversify.config.ts
:
(具体的绑定发生在inversify.config.ts
:)
container.bind<Weapon>(TYPES.Weapon).to(Katana)
So the reason why this is useful is that you have the ability to provide concrete classes at runtime.
(因此之所以有用,是因为您能够在运行时提供具体的类。)
You don't need to pre-define (hardcode) them in the class. (您无需在类中预定义(硬编码)它们。)