Tuesday, November 3, 2009

UnityContainer Lifetime Management extension methods

The following code snippet  registers the type MySingletonObject to the IMyObject interface as a singleton. The problem is that in order to get the UnityContainer type you need a references to the Microsoft.Practices.Unity.dll and in order to get the ContainerControlledLifetimeManager type you will need a reference to the Microsoft.Practices.ObjectBuilder2.dll

Now if the case is that you need more that ContainerControlledLifetimeManager type from Microsoft.Practices.ObjectBuilder2.dll then it’s worth the reference… if not then the following extension method could help you do the same as before without the need for a reference to Microsoft.Practices.ObjectBuilder2.dll (in a large project you will most likely have some base class library dll with common and shared types; create the extension method there…)


Using the extension method the code now looks like this:



Same idea can be applied for  ExternallyControlledLifetimeManager.

Note that Chris Tavares (from the p&p team) has mentioned in the p&p summit 2009 last month that the next release of Unity will have the Microsoft.Practices.ObjectBuilder2.dll most likely merged into the Unity assembly.