skip to the main content area of this page
Patterns and Practices

Unity Nested Containers - IUnityContainer and CreateChildContainer


The Unity Inversion of Control and Dependency Injection Container from Microsoft Patterns & Practices supports nested containers, where a Parent Container has the ability to create child containers. What is cool about the Parent-Child Relationship between UnityContainers is that by default Unity will search the local container to resolve a type mapping, and if not found, will navigate up to any Parent Containers to resolve the type. This provides the ability to override global ( parent ) type mappings with local ( child ) type mappings.

 

IUnityContainer and CreateChildContainer

IUnityContainer defines a method, called CreateChildContainer, that creates a child container.

 

UnityContainer parentContainer = new UnityContainer();
IUnityContainer childContainer = parentContainer.CreateChildContainer();

 

Search Nested Unity Containers From Child to Parent

What is cool is that when you try to resolve a type mapping in a child container and it is not found, Unity will automatically go to any parent Unity Containers to try and resolve the type.

 

Nested Unity Containers

 

Here is some sample code that creates a Parent Unity Container and two nested Child Containers. Since childContainer2 does not register an ILogger in its container, a request for ILogger from childUnityContainer2 will be fulfilled by the parentContainer. Since childContainer1 does register an ILogger in its container, the child container will resolve the type locally and not ask the parentContainer to try and resolve the type mapping.

 

UnityContainer parentContainer = new UnityContainer();
IUnityContainer childContainer1 = parentContainer.CreateChildContainer();
IUnityContainer childContainer2 = parentContainer.CreateChildContainer();

parentContainer.RegisterType<ILogger, NullLogger>
(new ContainerControlledLifetimeManager())
; childContainer1.RegisterType<ILogger, CustomLogger>
(new ContainerControlledLifetimeManager())
; // Should be NullLogger // From ParentContainer ILogger logger = childContainer2.Resolve<ILogger>(); logger.Log("Test"); // Should be CustomLogger // From LocalContainer ILogger logger2 = childContainer1.Resolve<ILogger>(); logger2.Log("Test");

 

Note that the code above is from the Unity CTP, so it is subject to change. In fact, the SetSingleton Method will most definitely be removed from the API when Unity goes into production.

 

Conclusion

The ability to create Nested Unity Containers and the default capability of child containers to request type mappings from Parent Unity Containers makes for some wonderful opportunities in our ASP.NET, Winform, and WPF Applications.

Hope this helps.

David Hayden


Tags: DependencyInjection, IoC, Unity


Topics



Popular Tags



Recent Links