admin管理员组

文章数量:1389928

I am using inversifyJs for DI in my typescript project. When using the decorator @multiInject, I am getting the error "Ambiguous match found for serviceIdentifier". I am following this example (.md). Why am I getting this error? Any help will be appreciated. Thanks.

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.

I am using inversifyJs for DI in my typescript project. When using the decorator @multiInject, I am getting the error "Ambiguous match found for serviceIdentifier". I am following this example (https://github./inversify/InversifyJS/blob/master/wiki/multi_injection.md). Why am I getting this error? Any help will be appreciated. Thanks.

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.
Share Improve this question asked Apr 19, 2020 at 1:39 Syed Hammad AhmedSyed Hammad Ahmed 2593 silver badges9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You are getting "Ambiguous match found for serviceIdentifier" because when you get the container you are using the "weapon" identifier and that is not correct.

Changing this line const ninja = container.get<INinja>('Weapon'); to const ninja = container.get<INinja>('Ninja'); should give you the desired output.

本文标签: