InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

Cannot multiInject named bindings

Open JbIPS opened this issue 2 years ago • 2 comments

Let's imagine the following class hierarchy:

interface Weapon {
}

interface BladedWeapon extends Weapon {
}

class Katana implements BladedWeapon {
}

class Stick implements Weapon {
}

Current bindings are following:

container.bind<Weapon>('Weapon').to(Stick).whenTargetNamed('stick');
container.bind<Weapon>('Weapon').to(Katana).whenTargetNamed('katana');

In one part of my code I would like to get all instances of Weapon interface:

@multiInject('Weapon') weapons: Weapon[];

In the other part I would like to get katana:

@inject('Weapon') @named('katana') katana: Katana;

Expected Behavior

@multiInject('Weapon') should return Stick and Katana, @named should only return Katana.

Current Behavior

I currently get an error

 Error: No matching bindings found for serviceIdentifier: 'Weapon'

Your Environment

  • Version used: 6.0.1
  • Environment name and version (e.g. Chrome 39, node.js 5.4): Node.js v19.3.0
  • Operating System and version (desktop or mobile): Desktop

Stack trace

  Error {
    message: 'No matching bindings found for serviceIdentifier: Symbol(Weapon)',
  }

  › _validateActiveBindingCount (node_modules/inversify/src/planning/planner.ts:113:15)
  › _getActiveBindings (node_modules/inversify/src/planning/planner.ts:91:3)
  › _createSubRequests (node_modules/inversify/src/planning/planner.ts:160:22)
  › <anonymous> (node_modules/inversify/src/planning/planner.ts:194:9)
  › Array.forEach (<anonymous>)
  › <anonymous> (node_modules/inversify/src/planning/planner.ts:193:20)
  › Array.forEach (<anonymous>)
  › _createSubRequests (node_modules/inversify/src/planning/planner.ts:164:18)
  › plan (node_modules/inversify/src/planning/planner.ts:240:5)
  › <anonymous> (node_modules/inversify/src/container/container.ts:623:25)

JbIPS avatar Mar 22 '23 09:03 JbIPS

I use this way to handle that "correctly" :

container.bind<Stick>('Stick').to(Stick);
container.bind<Katana>('Katana').to(Katana);

container.bind<Weapon>('Weapon').toService('Stick');
container.bind<Weapon>('Weapon').toService('Katana');

This way you can use @inject('Stick') or @multiInject('Weapon') given the situation

joelwurtz avatar Sep 11 '23 18:09 joelwurtz

Look at this example: https://github.com/Strauteka/inversify-bind-decorator

Strauteka avatar Sep 13 '23 05:09 Strauteka