di.js icon indicating copy to clipboard operation
di.js copied to clipboard

Services defined on parent injector depending upon services defined in child injector

Open petebacondarwin opened this issue 12 years ago • 1 comments

I want to have a root injector, which contains a provider for a service, A but I want to have a child injector that provides anothe service, B, which A depends upon:

module moduleB {
  @Provide(B)
  export function getB() { ... }
}

module moduleA {
  import {B} from modulateB;
  @Provide(A)
  export function getA(@Inject(B) b) { ... }
}

var rootInjector = new Injector([moduleA]);
var childInjector = new Injector([moduleB], rootInjector);

This doesn't work because you try the following:

childInjector.get(A);

The childInjector doesn't contain the A service so falls back to the rootInjector, which does. But then the params for A include B, an object that is only defined in the childInjector. Look up of the B object is only done on the rootInjector and so fails.

Now maybe this is the correct semantic, but it would prevent things like child injectors from overriding the services in a parent injector. I would imagine that a better algorithm would be to pass along the "youngest" (e.g. the child) injector along when looking up objects in a parent injector so that you can then "start again" at this youngest injector when looking up param dependencies of objects found in the parent injector.

petebacondarwin avatar Apr 20 '14 20:04 petebacondarwin

Yep, this is a known problem, still not sure what the best solution is ;-)

I'm against injecting B from child into A in the parent. That would be wrong. An object can only get instances from the same injector (same life scope) or parent injector (longer life scope). When injector goes away, I just wanna throw it away, without worrying that something in the parent is depending on it.

I think, in this case, we should automagically force a new instance of A, so that A is created in the child injector.

Something like: when creating a child injector, for each added (overridden) provider and for each "forced new instance", we also force new instances of all providers from parents that depends on any of these "new providers"... I think that's the most reasonable behavior.

vojtajina avatar Apr 21 '14 23:04 vojtajina