Nest.js中的multiInject

问题描述 投票:1回答:1

在Inversify.js中有multiInject装饰器,它允许我们将多个对象注入数组。此数组中的所有对象的依赖关系也会得到解决。

有没有办法在Nest.js中实现这一目标?

javascript node.js nestjs inversifyjs
1个回答
3
投票

没有直接相当于multiInject。你可以提供一个custom provider数组:

Example

试试这个sandbox的例子。

Injectables

假设您有多个@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!';
  }
}

Module

CatDog都可以在你的模块中使用(在那里提供或从另一个模块导入)。现在,您为Animal数组创建自定义标记:

providers: [
    Cat,
    Dog,
    {
      provide: 'MyAnimals',
      useFactory: (cat, dog) => [cat, dog],
      inject: [Cat, Dog],
    },
  ],

Controller

然后,您可以在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!';
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.