Revisiting XML Configurations In Unity
In the past I wrote a few tutorials about Unity application block. One of the things I wrote about was how to configure a Unity container using design time configuration. In this post I’m going to revisit that post and show you how the configurations changed (for the better) and are much more easier to work with in the current version of Unity (version 2).
The Unity Configuration Section
As in my previous post we will first start with a small example of Unity configuration section in order to understand it. Later I’m going to discuss the elements and how to configure them. So here is the configuration file:
As opposed to the configurations we mad ein Unity’s first version this is much shorter. One thing to notice is the use of Xml namespace (http://schemas.microsoft.com/practices/2010/unity) which you will need to use in the Unity configuration section in order to get Intellisense.
Unity Elements Changes
Lets check what was changed.
Aliases – the first thing to notice is the absence of the typeAliases container element. Instead of it you can register your aliases one after another. Also, the element name typeAlias was changed to alias. This is no big deal but it is making the aliases registration a little more shorter.
Containers – like the aliases, the containers element was disposed. You will create a container element for each container with a relevant name. In every container you will register types and instances to be resolved. Instead of the Types element and the Type element you will use the register or instance elements. Inside these elements you will configure things like the constructor injection that I used in the example.
Building the Runtime Example
I’m using the same example which I used in the previous post. Here are the classes:
When you want to use the Xml configurations Unity exposes a container method which is called LoadConfiguration which will load the configurations for you. Here is an example of how to use it:
First you create the Unity container. Then you use the container’s LoadConfiguration method in order to load the configurations you made into the container. In the example I use the container name (MyContainer) from the configuration file. Then you can use Unity resolve method to get the relevant runtime implementation. Easy as that.
Even though I prefer to use runtime configuration in order to configure my Unity container, there are times that the specifications don’t change and a design time configuration can be used. In this post I showed you how to use Unity’s current version Xml configuration. If your are using the previous version of Unity you can find details about its configurations in my old post.