This has been a bad month for blogging. Intense work and weekend personal affairs kept me away from the .NET Brainwork blog admin console. But I’ll try to change things from now on, and keep my monthly post rate above 5. I’ve thought about writing a small introduction on Unity, from the Enterprise Library framework.
Unity is an Inversion of Control ( IoC ) Container and Dependency Injection Tool from Microsoft Patterns & Practices that uses ObjectBuilder 2.0 as its dependency injection engine. You are probably thinking: “What the hell does Inversion of Control mean!?” or “What’s Dependency Injection?”. Well a Dependency Injection container is a fabulous tool that allows you to write decoupled software, making it transparently adapt to new interface scenarios. What this means is, your application will now be able to work with decoupled functional modules by implementing an interface-driven architecture. “How does this work?” – you say. Well in Unity you can register an external assembly class to be used by your aplication, by associating it with the application required interfaces. It stores registrations and mappings between types and can instantiate the appropriate concrete types on demand. Let’s take a logging component as an example. In this example we wish to develop an application that can support different logging platforms. we could define the unity section in our web.config or app.config like this:
<unity> <typeAliases> <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity"/> <typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity"/> <typeAlias alias="IMyInterface" type="MyObjects.IMyInterface, MyObjects"/> <typeAlias alias="MyRealObject" type="MyObjects.MyRealObject, MyObjects"/> <typeAlias alias="MyOtherObject" type="MyObjects.MyOtherObject, MyObjects"/> <typeAlias alias="ILogger" type="MyObjects.ILogger, MyObjects"/> <typeAlias alias="MyLogger" type="MyObjects.MyLogger, MyObjects"/> <typeAlias alias="MyFastLogger" type="MyObjects.MyFastLogger, MyObjects"/> </typeAliases> <containers> <container name="containerOne"> <types> <type type="IMyInterface" mapTo="MyRealObject"/> <type type="ILogger" mapTo="MyFastLogger"> <lifetime type="singleton"/> </type> <type type="ILogger" mapTo="MyLogger" name="StandardLogger"> <lifetime type="singleton"/> </type> <type type="ILogger" mapTo="MyFastLogger" name="SuperFastLogger"> <lifetime type="external"/> </type> </types> </container> </containers> </unity>
This example does this by configuration. You can also do this by code, although I find this more interesting to look at for this article. So this is where the magic makes sense. All registered types are kept in one or more containers, although in this example we’re using only one. I’ve called it “containerOne”. At runtime, this container is loaded (in an ASP.NET application, this is usually done in global.asax, in the application start event) and underlying/registered types will be made available to the engine.
Notice line number 7: what this line does is say that the class MyFastLogger will be implementing the ILogger interface. Every time your application instantiates ILogger, it will be instantiating the MyFastLogger type in the background. Nice huh? If you want to use a different logging assembly for this, just register it and that’s it. The lifetime nodes are there because Unity container manages the creation and resolution of objects based on a lifetime you specify when you register the type of an existing object, or on the default lifetime if you do not specify a lifetime manager for it to use. The Unity Application Block includes the two lifetime managers specified above, ContainerControlledLifetimeManager and ExternallyControlledLifetimeManager, but you can create your own with your specific behaviour.
The container types are initialized internally like this:
UnityContainer myContainer = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers["containerOne"].Configure(myContainer);
Application["MyContainer"] = myContainer;
And in our application, it all comes down to this:
ILogger myExampleInstance = myContainer.Resolve(loggerType);
output = myExampleInstance.MyInterfaceMethod("Unity rocks!");
My logging object will be internally instantiated with my registered class, and the interface member is used. So here it is, a quick example, for a quick start.So if you’re into design patterns, download Enterprise Library 4, complement this article with this MSDN walkthrough and happy coding!
Technoratti Tags: Unity, Enterprise Library
















5 comments so far
Thanks for a great article, and the code samples are awesome!
-Joseph Marinaccio
January 31st, 2009I’m just in the process of learning Unity (having been forced to use it instead of Castle Windsor in an MVC application, which isn’t suitable for use in Medium Trust).
I’m trying to replicate what Castle Windsor calls lifestyle=”PerWebRequest” in its configuration file:-
I don’t really understand the role of the two lifetime managers you mentioned – ContainerControlledLifetimeManager and ExternallyControlledLifetimeManager. Can these be configured to replicate the PerWebRequest behaviour?
Thanks for the useful article,
Steve
January 13th, 2010Hi Steve
January 15th, 2010Sorry for the delay, but’s these are busy times. From what I know of Castle Windsor’s PerWebRequest lifestyle, it’s much like the Request object in ASP.NET in which one instance of the object is created per web request.
You can have the same behavior if you make a custom LifetimeManager or by handling instance/type registrations at WebRequestStart-time with the appropriate controller.
Remember that the default lifetime for objects registered using the RegisterInstance method is the ContainerControlledLifetimeManager, which causes them to behave like a singleton (same instance resolve every time).
Thanks for the article. A general question: I’m currently trying to work my way through the Unity Event Broker Extension quick start, and I’m having difficulties. Is there any kind of online forum to post questions to the Unity community that you know of?
February 9th, 2010Trackbacks
Add a comment