Global Unity Container Tip

May 6, 2009 at 8:06 AM

I'm going to use Unity to create a reusable assembly which is just a simple class library.
This assembly should not knoq where and how it will be used. It only has some interface to interact with.

What is the best and correct way to provide IUnityContainer for this assembly?
Using static variable doesn't sound good for me. Neither storing container in a Thread/HttpContext etc.

Thanks in advance for the help!
May 13, 2009 at 4:06 AM


May 13, 2009 at 6:50 AM
Edited May 13, 2009 at 6:51 AM

We use a static class ( in a suitably low level common assembly ) that contains 2 internal Dictionary<string, IUnityContainer>.  We initialise from a .config file which populates the default dictionary, then provide a series of methods to override the containers ( mostly for unit testing ).  These get stored in the second dictionary.

Second, there is a Property to retrieve the "default" container ( container with no name ) and another method to retrieve a named container.  Both of these check the override dictionary first.

Third, there is a method to Reset the internal state by clearing the second dictionaries, and optionally rebuilting the default containers from config

Lastly, we have implemented a custom unity extension to track registrations and instances to allow a CanResolve<T> extension method on IUnityContainer.  This allowed us to query for whether an interface can resolve without ObjectBuilder throwing an exception.


Using this static class ensures most ( if not all ) plumbing code is removed from the developer's view and the same containers are used across our entire system making unit testing simple. 

Hope this helps.





May 13, 2009 at 7:45 AM


So you are using static variable (not even ThreadStatic).


May 13, 2009 at 8:39 AM

Our container configuration is static and doesn't change during the application lifetime so the situation works for us.

The objects resolved are either using the default or singleton lifetime managers so we don't have any threading issues.  The only part that is synchronised is the container configuration

May 13, 2009 at 9:24 AM

Ok. Thanks.

I think I will stay with my static class (but using ThreadStatic).

If anubody has some comments please post.