CreateChildContainer does not work like in documentation

Feb 15, 2008 at 6:25 PM
I've tried to create a child container but this does not seems to work like in documentation.
// In documentation
IUnityContainer parentCtr = new UnityContainer();
// Create nested child container in parent container
IUnityContainer childCtr = parentCtr.CreateChildContainer();

But CreateChildContainer is not part of IUnityContainer interface
Feb 15, 2008 at 9:43 PM
The docs may have a minor issue here. The CreateChildContainer method is on the IUnityParentContainer interface, not IUnityContainer. The reasons for this are:

  • We didn't want to force folks to have to deal with hierarchical containers unless they actually need them.
  • We didn't want to add more associated properties (like Parent or Children) and expose the implementation details.
  • And the big one - using the configuration API you could seriously screw yourself up.

Consider what happens if you do this (assuming that CreateChildContainer was on the interface):

IUnityContainer parent = new UnityContainer()
.Register<IFoo, Foo>()
.Register<IBar, Bar>();

What container does Parent now reference? Answer - the child. The parent container is now forever out of reach.

Putting CreateChildContainer on a separate interface breaks this chain, and avoids this particular unsubtle issue.

The easiest way to get your code working would be:

UnityContainer parentCtr = new UnityContainer(); // <-- concrete type, not interface
IUnityContainer childCtr = parentCtr.CreateChildContainer();