inversify / InversifyJS

A powerful and lightweight inversion of control container for JavaScript & Node.js apps powered by TypeScript.
http://inversify.io/
MIT License
11.21k stars 715 forks source link

How to get all by each child? #1471

Open shtse8 opened 2 years ago

shtse8 commented 2 years ago

Consider this setup:

container.bind<Config>(TYPES.Config).toConstantValue(a).whenParentNamed('a')
container.bind<Config>(TYPES.Config).toConstantValue(b).whenParentNamed('b')
container.bind<Config>(TYPES.Config).toConstantValue(c).whenParentNamed('c')
container.bind<Runner>(TYPES.Runner).to(Runner).inRequestScope()

I can get all configs by

const configs = container.getAll<Config>(TYPES.Config) // all configs returned

Also, I can get one parent by

const runner = container.getByNamed<Runner>(TYPES.Runner, 'a')  // runner with a config returned

But, how to get all runners for each config?

const runners = container.getAll<Runner>(TYPES.Runner) // Error: Ambiguous match found for serviceIdentifier: Symbol(Config)

Or, is it possible to get all named on Config, so that I can get all by one by one?

shtse8 commented 2 years ago

Finally I can achieve this. Here is my implementation. Just wondering if it is proper way to do.

setup

for (const config of configs)
  container.bind<Config>(TYPES.Config).toConstantValue(config).whenParentTagged('config', config)
container.bind<Runner>(TYPES.Runner).to(Runner)
container.bind<interfaces.Factory<Runner>>(TYPES.RunnerFactory).toFactory<Runner, [Config]>(context => config => context.container.getTagged<Runner>(TYPES.Runner, 'config', config))

usage

const configs = container.getAll<Config>(TYPES.Config)
const runnerFactory = container.get<interfaces.Factory<Runner>>(TYPES.RunnerFactory)
const runners = configs.map(runnerFactory)