Should factories registered at the parent level get access to the child container being used?

Apr 29, 2009 at 4:11 PM

I have a registration for Foo in the parent container, and its factory requires a Bar.
A child container has a registration for Bar.
If I resolve Foo on the child container, should Foo's factory be given the container I called resolve with, and hence be able to get the Bar it needs?

i.e. Should this work:

 public class FunqTest
  class Bar

  class Foo
   public Foo(Bar b)

  public void ResolveDependenciesFromChildLevel()
   var parent = new Container();
   parent.Register(c => new Foo(c.Resolve<Bar>()));

   var child = parent.CreateChildContainer();
   child.Register(_ => new Bar());

   var foo = child.Resolve<Foo>();

Apr 30, 2009 at 10:14 AM
I've worked it out.
If I register Foo with .ReuseWithin(ReuseScope.Container) then it gets built in the child container and resolves Bar correctly.
Apr 30, 2009 at 3:23 PM
Indeed, Reuse is the thing that controls where the instance lives and therefore where it's constructed.
The default is Hierarchy, meaning that it's created where it's registered, and reused from that container on to child containers. In this case, it would be wrong for a class in a parent container to keep a reference (passed-in when constructed) to an object that was created by a child container and probably may be disposed with it.

Container reuse means the instance is created in each container, so whatever it needs will be resolved from there up the hierarchy.