javascripttypescriptdependency-injectioninversifyjs

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


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.com/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.

Solution

  • 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.