Nest.js 中的 multiInject
multiInject in Nest.js
在Inversify.js中有multiInject
装饰器允许我们将多个对象作为数组注入。该数组中所有对象的依赖关系也已解决。
在Nest.js中有什么方法可以做到这一点吗?
没有直接等同于 multiInject
。您可以提供一个带有 custom provider 的数组:
例子
在此 sandbox 中试用示例。
注射剂
假设您有多个 @Injectable
类 实现接口 Animal
.
export interface Animal {
makeSound(): string;
}
@Injectable()
export class Cat implements Animal {
makeSound(): string {
return 'Meow!';
}
}
@Injectable()
export class Dog implements Animal {
makeSound(): string {
return 'Woof!';
}
}
模块
类 Cat
和 Dog
都在您的模块中可用(在那里提供或从另一个模块导入)。现在您为 Animal
:
的数组创建自定义标记
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (cat, dog) => [cat, dog],
inject: [Cat, Dog],
},
],
控制器
然后您可以像这样在控制器中注入和使用 Animal
数组:
constructor(@Inject('MyAnimals') private animals: Animal[]) {
}
@Get()
async get() {
return this.animals.map(a => a.makeSound()).join(' and ');
}
如果 Dog
有额外的依赖项,如 Toy
,这也有效,只要 Toy
在模块 (imported/provided) 中可用:
@Injectable()
export class Dog implements Animal {
constructor(private toy: Toy) {
}
makeSound(): string {
this.toy.play();
return 'Woof!';
}
}
只需对@kim-kern 的出色解决方案进行细微调整,您就可以使用该解决方案,但可以避免添加新条目的少量开销...
替换
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (cat, dog) => [cat, dog],
inject: [Cat, Dog],
},
],
与
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (...animals: Animal[]) => animals,
inject: [Cat, Dog],
},
],
这只是次要的,但不必在 3 个地方添加一个新的,而是减少到 2。当你有几个时加起来,减少出错的机会。
nest 团队也在努力使这更容易,您可以通过这个 github 问题进行跟踪:https://github.com/nestjs/nest/issues/770
在Inversify.js中有multiInject
装饰器允许我们将多个对象作为数组注入。该数组中所有对象的依赖关系也已解决。
在Nest.js中有什么方法可以做到这一点吗?
没有直接等同于 multiInject
。您可以提供一个带有 custom provider 的数组:
例子
在此 sandbox 中试用示例。
注射剂
假设您有多个 @Injectable
类 实现接口 Animal
.
export interface Animal {
makeSound(): string;
}
@Injectable()
export class Cat implements Animal {
makeSound(): string {
return 'Meow!';
}
}
@Injectable()
export class Dog implements Animal {
makeSound(): string {
return 'Woof!';
}
}
模块
类 Cat
和 Dog
都在您的模块中可用(在那里提供或从另一个模块导入)。现在您为 Animal
:
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (cat, dog) => [cat, dog],
inject: [Cat, Dog],
},
],
控制器
然后您可以像这样在控制器中注入和使用 Animal
数组:
constructor(@Inject('MyAnimals') private animals: Animal[]) {
}
@Get()
async get() {
return this.animals.map(a => a.makeSound()).join(' and ');
}
如果 Dog
有额外的依赖项,如 Toy
,这也有效,只要 Toy
在模块 (imported/provided) 中可用:
@Injectable()
export class Dog implements Animal {
constructor(private toy: Toy) {
}
makeSound(): string {
this.toy.play();
return 'Woof!';
}
}
只需对@kim-kern 的出色解决方案进行细微调整,您就可以使用该解决方案,但可以避免添加新条目的少量开销...
替换
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (cat, dog) => [cat, dog],
inject: [Cat, Dog],
},
],
与
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (...animals: Animal[]) => animals,
inject: [Cat, Dog],
},
],
这只是次要的,但不必在 3 个地方添加一个新的,而是减少到 2。当你有几个时加起来,减少出错的机会。
nest 团队也在努力使这更容易,您可以通过这个 github 问题进行跟踪:https://github.com/nestjs/nest/issues/770