在 Inversify.js 中有一个multiInject
装饰器,它允许我们将多个对象作为数组注入。此数组中的所有对象的依赖关系也已解决。
有什么方法可以在 Nest.js 中实现这一点吗?
在 Inversify.js 中有一个multiInject
装饰器,它允许我们将多个对象作为数组注入。此数组中的所有对象的依赖关系也已解决。
有什么方法可以在 Nest.js 中实现这一点吗?
没有直接等价于multiInject
。不过,您可以为数组提供自定义提供程序:
试试这个沙箱中的例子。
假设您有多个@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
像这样在 Controller 中注入和使用数组:
constructor(@Inject('MyAnimals') private animals: Animal[]) {
}
@Get()
async get() {
return this.animals.map(a => a.makeSound()).join(' and ');
}
如果Dog
有额外的依赖项,这也有效Toy
,只要Toy
在模块中可用(导入/提供):
@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