Nest.js 中的 multiInject

Que*_*wer 2 javascript node.js inversifyjs nestjs

Inversify.js 中有一个multiInject装饰器,允许我们将多个对象作为数组注入。此数组中所有对象的依赖关系也已解决。

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

Kim*_*ern 13

没有直接等价于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!';
  }
}
Run Code Online (Sandbox Code Playgroud)

模块

CatDog都在您的模块中可用(在那里提供或从另一个模块导入)。现在您为以下数组创建一个自定义令牌Animal

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

控制器

然后,您可以Animal像这样在控制器中注入和使用数组:

constructor(@Inject('MyAnimals') private animals: Animal[]) {
  }

@Get()
async get() {
  return this.animals.map(a => a.makeSound()).join(' and ');
}
Run Code Online (Sandbox Code Playgroud)

如果Dog有额外的依赖项(如 )Toy,只要Toy在模块中可用(导入/提供),这也有效:

@Injectable()
export class Dog implements Animal {
  constructor(private toy: Toy) {
  }
  makeSound(): string {
    this.toy.play();
    return 'Woof!';
  }
}
Run Code Online (Sandbox Code Playgroud)