InversifyJS @multiInject 不工作,抛出错误 "Ambiguous match found for serviceIdentifier"

InversifyJS @multiInject not working, throws error "Ambiguous match found for serviceIdentifier"

我在我的打字稿项目中使用 inversifyJs 作为 DI。使用装饰器@multiInject 时,出现错误"Ambiguous match found for serviceIdentifier"。我正在关注这个例子 (https://github.com/inversify/InversifyJS/blob/master/wiki/multi_injection.md)。为什么会出现此错误?任何帮助将不胜感激。谢谢

import 'reflect-metadata';
import { Container, multiInject, injectable, } from 'inversify';

interface IWeapon {
  name: string;
}

interface INinja {
  weapons: IWeapon[],
  displayWeapons(): void,
}

@injectable()
class Katana implements IWeapon {
  public name = 'Katana';
}

@injectable()
class Shuriken implements IWeapon {
  public name = 'Shuriken';
}

@injectable()
class Ninja implements INinja {
  public weapons: IWeapon[];

  constructor(
    @multiInject('Weapon') _weapons: IWeapon[],
  ) {
    this.weapons = _weapons;
  }

  public displayWeapons = () => {
    console.log(this.weapons[0].name, this.weapons[1].name);
  }
}

const container = new Container();

container.bind<INinja>("Ninja").to(Ninja);
container.bind<IWeapon>("Weapon").to(Katana);
container.bind<IWeapon>("Weapon").to(Shuriken);

const ninja = container.get<INinja>('Weapon');
ninja.displayWeapons(); // Should display all weapons.

您收到“为 serviceIdentifier 找到的模糊匹配项”,因为当您获取容器时,您使用的是“武器”标识符,而这是不正确的。

将此行 const ninja = container.get<INinja>('Weapon'); 更改为 const ninja = container.get<INinja>('Ninja'); 应该会得到所需的输出。