nicojs / typed-inject

Type safe dependency injection for TypeScript
Apache License 2.0
448 stars 23 forks source link

Allow multiple tokens for the same value #65

Open dmeehan1968 opened 1 year ago

dmeehan1968 commented 1 year ago

It would be useful if the provide... functions would accept multiple tokens. This would be useful for describing interfaces that are implemented in an aggregate concretion, for example:

interface GetThing { get(id: string) : Thing }
interface PutThing { put(thing: Thing): void }

class ThingRepository implements GetThing, PutThing {
  get(id:string) { return 'thing' }
  put(thing: Thing) { }
}

const injector = createInjector().provideClass(['GetThing','PutThing', 'ThingRepository'], ThingRepository)

In this way, consumers can specify the interface they want, and get a concretion which provides that, even if it provides other things we don't care about.

At present we can specify multiple provide... calls, but in this case, the instance/value will be created for each token specified by a consumer, where we might actually intended to have a singleton or transient scope. Whilst it would be possible to provide a factory that deals with this, its somewhat obtuse and repetitive if we want to use the pattern extensively.