InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

How to get all by each child?

Open shtse8 opened this issue 3 years ago • 1 comments

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 avatar Jul 05 '22 14:07 shtse8

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)

shtse8 avatar Jul 05 '22 14:07 shtse8