InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

getAll - Error: No matching bindings found for serviceIdentifier

Open cts-tradeit opened this issue 3 years ago • 4 comments

Expected Behavior

class StartupCallback {}

If I have container that contains 0 bindings of class StartupCallback and I do getAll I get empty array.

Current Behavior

class StartupCallback {}

If I have container that contains 0 bindings of class StartupCallback and I do getAll I get:

Error: No matching bindings found for serviceIdentifier

Possible Solution

Get all should return empty array if 0 items are bound. Usually when resolving by all (array) it is for components like lifecycle callbacks and initializes which count may vary across environments. It should be possible to have between 0 and n of these instead of between 1 and n, as in environment without single callback we have to provide noop binding.

Your Environment

version: 6.0.1

cts-tradeit avatar Jun 27 '22 10:06 cts-tradeit

Are there aany news on thi sissue?

Deathrage avatar Nov 15 '22 19:11 Deathrage

Old, but maybe this still helps you.

A nasty fix is to monkey patch container.getAll:

container.ts

import { Container } from "inversify"

export const container = new Container()

// types taken from `inversify/lib/interfaces.d.ts`
export type Newable<T> = new (...args: any[]) => T;
export interface Abstract<T> {
    prototype: T;
}
export type ServiceIdentifier<T = unknown> = (string | symbol | Newable<T> | Abstract<T>);

// monkey patching `container.getAll`
const getAll = container.getAll.bind(container)
container.getAll = <T>(serviceIdentifier: ServiceIdentifier<T>): T[] => {
  try {
    return getAll(serviceIdentifier)
  }
  catch (err) {
    return []
  }
}

Now, this will no longer throw an error, but instead return an empty array:

index.ts

import { container } from "./container"

// class that is not bound.
class MyService {
}


async function main() {
  let services = container.getAll(MyService)
  console.log('🎉');
}

main()

logikaljay avatar Dec 15 '23 22:12 logikaljay

Sorry for the lack of response here, the project went through an unmaintained period but we have been publishing releases again recently (6.0.2 at the end of October 2023)

--

Similar to #1359 I think this would be a great feature for the official library, imo we should aim to get this into an official release. cc @PodaruDragos

Jameskmonger avatar Dec 17 '23 14:12 Jameskmonger

Added to milestone 6.1.0 pending agreement from other contributors.

Jameskmonger avatar Dec 17 '23 14:12 Jameskmonger