1

I am new to nodejs and typescript, coming from C#. I want to use dependency injection in my project and found that the most popular package is inversify.

I started using it but I don't like the fact that I have to add decorators all over.

for example it bothers me that I need to add @inject before parameters in the constructor:

public constructor(
    @inject(TYPES.Weapon) katana: Weapon,
    @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
)

This mean every class has to know the TYPES object...

I don't understand why @inject needs the string literal and can't inject just on the basis of the type...

Is there a neater way to do this?

4

1 回答 1

1

与严格类型的语言相比,TypeScript 类型在运行时不存在。可以在运行时使用类型信息进行依赖注入,但方式有限。通过使用emitDecoratorMetadataTypeScript 选项,可以获取构造函数参数类型并将它们用于 DI。

示例是injection-jsAngular 注入器,它是从库中提取出来供独立使用的。在启用 DI 的类上只@Injectable需要使用装饰器,@Inject参数装饰器是可选的。

限制是只能以这种方式注入类实例:

constructor(foo: FooClass) {}

泛型被忽略和丢弃:

constructor(foo: FooClass<Bar>) {}

其他类型被忽略并导致 DI 错误:

constructor(foo: fooSymbol) {}

constructor(foo: 'foo string provider') {}

这同样适用于 InversifyJS

在具体注入的情况下,您可以像往常一样简单地定义构造函数参数,而无需使用 @inject 装饰器。

InversifyJS 还支持 TypeScript 的构造函数分配,因此您可以在参数中使用私有或受保护的访问修饰符,并且容器在注入依赖项时不会遇到问题

如果它们是类,则可以省略,但在列出的示例中是@inject一个符号,并且是一个在运行时不存在的接口,因此是必要的。WeaponThrowableWeaponTYPES.WeaponWeapon@inject

于 2019-04-01T07:27:11.663 回答