InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

What should I do if I want to multiInject multiple targetName?

Open ytetsuro opened this issue 3 years ago • 3 comments

I want a Ninja per Weapon in every game board class.

@injectable()
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@injectable()
class Shuriken implements Weapon {
    public hit() {
        return "hit!";
    }
}

@injectable()
class Ninja implements Warrior {
    public constructor(
	    @inject(TYPES.Weapon) private readonly weapon: Weapon
    ) {
    }

    public fight() { return this._katana.hit(); }
}

@injectable()
class GameBoard {
    public constructor(
	    @multiInject(TYPES.Warrior) private readonly warriors: Warrior[]
    ) {
    }
}

const container = new Container();
container.bind(TYPE.Weapon).to(Shuriken).whenTargetName('shuriken');
container.bind(TYPE.Weapon).to(Katana).whenTargetName('katana');
container.bind(TYPE.Warrior).to(Ninja);
container.bind(GameBoard).to(GameBoard);

// ???

Expected Behavior

I want an instance that is equivalent to the following code.

new GameBoard([
  new Ninjya(new Katana()),
  new Ninjya(new Shuriken()),
]);

Current Behavior

Can't do this currently?

ytetsuro avatar Mar 12 '21 05:03 ytetsuro

I think the best way to do this would be to use a factory.

dcavanagh avatar Mar 30 '21 12:03 dcavanagh

@dcavanagh

Thanks for taking the time to reply. I think the only current solution is probably to create a factory. Does inversifyJS want to change to allow multiple target names in multiInjection? Is it worth the PR to make that change?

ytetsuro avatar Apr 05 '21 15:04 ytetsuro

@ytetsuro we are pretty swamped trying to revive this project. Are you interested in helping out?

Could you describe your proposal some more and we can have a discussion about it.

dcavanagh avatar Apr 07 '21 15:04 dcavanagh