Search code examples
javascripttypescriptdependency-injectioninversifyjs

Inversify throws "Ambiguous match found for serviceIdentifier" when a second binding is attempted


Did my diligence and the following are not the scenario I am experiencing.

Also referred to the Official MultiInject Documentation.


In my inversify.config.ts file I have the following

const SAContainer = new Container();

// Bot Command Handler bindings
SAContainer.bind<ICommandHandler>(TYPES.CommandHandlers).to(AboutCommand);
SAContainer.bind<ICommandHandler>(TYPES.CommandHandlers).to(AccountAgeCommand);

And both files are as follows:

@injectable()
export class AboutCommand implements ICommandHandler {
  // ...
}

@injectable()
export class AccountAgeCommand implements ICommandHandler {
  // ...
}

The exception that is thrown is:

Error: Ambiguous match found for serviceIdentifier: CommandHandlers
Registered bindings:
 AboutCommand
 AccountAgeCommand
 ...stack trace excluded

When I uncomment one of the bindings, so that there is only one, it works as expected. But when I attempt to bind 2 or more in this fashion, I get the error message. What have I missed?

The error is thrown the when the first dependency is pulled. In the application this is the application object and composition root.

SAContainer.bind<App>(App).toSelf().inSingletonScope();

const application = SAContainer.get<App>(App); // Error thrown here

Solution

  • There was apparently a single class that escaped code analysis and search due to not adhering to the use of the TYPES object. This class implemented an injection that was causing this issue.

    Problem code:

    @injectable()
    export class RaidHandler implements IRaidStreamEvent {
        constructor(
            @inject(ApiClient) private apiClient: ApiClient,
    >>      @inject('CommandHandlers') commandHandlers: shoutoutCommand,
            @inject(TYPES.Logger) private logger: winston.Logger,
        ) {
    

    Since this did not adhere to the accepted practice used in the code base, this bug hid from me and those involved in searching it down.