【发布时间】:2019-03-24 12:52:38
【问题描述】:
在 Inversify.js 中有 multiInject 装饰器,它允许我们将多个对象作为数组注入。此数组中所有对象的依赖关系也已解析。
有没有办法在 Nest.js 中实现这一点?
【问题讨论】:
标签: javascript node.js nestjs inversifyjs
在 Inversify.js 中有 multiInject 装饰器,它允许我们将多个对象作为数组注入。此数组中所有对象的依赖关系也已解析。
有没有办法在 Nest.js 中实现这一点?
【问题讨论】:
标签: javascript node.js nestjs inversifyjs
没有直接等效于multiInject。不过,您可以提供带有 custom provider 的数组:
试试这个sandbox中的例子。
假设您有多个实现Animal 接口的@Injectable 类。
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],
},
],
然后您可以像这样在 Controller 中注入和使用 Animal 数组:
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
【讨论】: