问题描述
在Inversify.js中有 multiInject
装饰器,允许我们将多个对象作为数组注入。此数组中所有对象的依赖关系也都已解决。
In Inversify.js there is multiInject
decorator that allow us to inject multiple objects as array. All objects' dependencies in this array resolved as well.
有没有办法在Nest.js中实现这一点?
Is there any way to achieve this in Nest.js?
推荐答案
没有直接相当于 multiInject
。您可以使用提供数组:
There is no direct equivalent to multiInject
. You can provide an array with a custom provider though:
试试这个实例。
假设您有多个 @Injectable
类,它们实现了接口 Animal
。
Let's assume you have multiple @Injectable
classes that implement the interface 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
数组创建自定义标记:
Module
The classes Cat
and Dog
are both available in your module (provided there or imported from another module). Now you create a custom token for the array of Animal
:
providers: [
Cat,
Dog,
{
provide: 'MyAnimals',
useFactory: (cat, dog) => [cat, dog],
inject: [Cat, Dog],
},
],
控制器
然后,您可以在Controller中注入并使用 Animal
数组像这样:
constructor(@Inject('MyAnimals') private animals: Animal[]) {
}
@Get()
async get() {
return this.animals.map(a => a.makeSound()).join(' and ');
}
如果 Dog
还有其他依赖项,例如 Toy
,只要玩具
是在模块中可用(导入/提供):
This also works if Dog
has additional dependencies like Toy
, as long as Toy
is available in the module (imported/provided):
@Injectable()
export class Dog implements Animal {
constructor(private toy: Toy) {
}
makeSound(): string {
this.toy.play();
return 'Woof!';
}
}
这篇关于Nest.js中的multiInject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!