As I promised in part 1 I will give you an intro of the available frameworks that support Ioc. First in the row is the Unity Framework. This framework will be part of Enterprise Library 4.0. They just released a first CTP (can be found on CodePlex). I’m quite enthusiastic about this framework and like Mr Borat would say “Is naaizzz”.
The building block where Unity is built on, exists since the first version of Enterprise Library and is called ObjectBuilder. ObjectBuilder was one of the first Dependency Injection frameworks available for .Net, but it has lived a silent life since then. I think this was caused by the complex interface of the API and the lack of documentation.
Ok, enough bla bla! Let’s take a look at the Unity framework:
I made a small class that will do a HelloWorld, the HelloWorldService. Like every Ioc container, the container needs to be configured. Unity framework allows configuration from code or an xml configuration file. From code it looks like this:
IUnityContainer container = new UnityContainer(); container.Register();
In a configuration file it looks like this:
Ok nothing shocking here. A typical config section and also a typical ioc config. But there is something about the schema I want to point out to you. <containers>. So we have the possibility to have multiple containers . You can give a container a name, the default container is the nameless container. I found this in the code, although there is already documentation in the package (Keep up the great job guys!). Now let’s see how we can use the HelloWorldService from code:
IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection(“unity“); section.Containers.Default.GetConfigCommand().Configure(container); IHelloWorldService service = container.Get();
I like the concept that they decoupled configuration from the container itself, but a small factory could ease the job. There is even another project called “Delta” on CodePlex that is creating an alternative configuration option.So, the next topic is about lifetime management. Most IoC containers support singleton and transient objects. Singleton means that once an object is created it will only exist once in the container . With transient you get a new object every time you request the object. Let’s put this to practice. In the config file:
In code:
Console.WriteLine(container.Get(“transientHelloWorld“).HelloWorld(“Thomas Annerel“)); Console.WriteLine(container.Get(“transientHelloWorld“).HelloWorld(“Thomas Annerel“)); Console.WriteLine(“Singleton“); Console.WriteLine(container.Get(“singletonHelloWorld“).HelloWorld(“Thomas Annerel“)); Console.WriteLine(container.Get(“singletonHelloWorld“).HelloWorld(“Thomas Annerel“));
The result:
In this example I’ve shown you how you can manage the lifestyle of an Object. Another small feature is that you can give a type a name and use that name to get an instance. Next feature is dependency injection. Unity supports all types of Dependency Injection, Constructor, Property and Interface injection, it even supports injection of strings. So let’s give it a try. I created an improved version of the HelloWorldService. In this version the message (a string) is injected and the second object hosted by unity is injected to do the formatting (just a simple string.ToUpper(), nothing fancy). So here is the config:
The code behind MessageInjectionHelloWorldService:
#region Properties
///
/// The injected formatter
///
[Dependency]
public IMessageFormatter Formatter
{
get
{
return formatter;
}
set
{
formatter = value;
}
}
#endregion
#region Override Properties
///
/// The message of HelloWorld
///
[Dependency(“HelloWorldMessageString“)]
public string MessageFormat
{
get
{
return helloWorldMessageFormat;
}
set
{
helloWorldMessageFormat = value;
}
}
#endregion
The attribute on the properties tells the ObjectBuilder behind Unity to inject an instance into this class. The attribute describes who to inject. The cool thing is that you can inject value types into an instance. The discussion about what to inject and what not is going to rise since the configuration of Unity can’t replace the need for custom configuration sections.
And now the result:
A pity is that there is no way to configure the dependencies in the configuration file. Maybe this is a feature that’s not implemented (yet).
So, I think I covered the most important stuff of an IoC container, except some features that are totally new in IoC land.
The first one is hierarchical containers. You can’t configure it using the configuration file, but it can be easily done in code. You can actually add a child container to every Unity container. In this child container you can overrule mappings of the parent container. It’s like object inheritance. This is a unique feature and I love it. This will make overriding the container in some circumstances (like UnitTesting) a lot easier.
Another great feature is that ObjectBuilder isn’t hidden away, this means that you can inject in classes that are not hosted in the container, you only need to create them using the ObjectBuilder. In the following example we ask the container to create a Form. If the form has any dependencies these will be automatically injected.
container.Get());
Summary
Lets put all the pros and cons together:
Pros:
- Can contain multiple containers.
- Container can be configured using code or a config file, letting the door open for other configuration options.
- API Interface supports generics, so no unnecessary casts.
- Container Hierachy.
- Can inject in objects that are not in the container, using the Object Builder functionality.
- Supports 3 sorts of Dependency Injection, namely constructor, property and method injection.
- Can inject instances and value types.
Cons:
- Not everything is configurable yet using the app.config.
- Missing some options in creating custom lifestyles (for singleton per HttpRequest in web applications).
Conclusion: this is the first CTP of Unity framework. I think this is a great start but still needs some work. I think it’s a great first candidate for our IoC DSL.
In my opinion, a very very bad point of Unity is the fact that you have to mark the properties / constructors that you want to use DI onto, with [Dependency] / [DependencyConstructor] attributes. The use of the IoC container is supposed to be transparent (hence the term Inversion of Control) … here, the container is invading your code !
Ayende has written his own review of Unity and he founds several additional show-stoppers:
http://www.ayende.com/Blog/archive/2008/02/24/Reviewing-Unity.aspx
Anyway, this is still pre-release code so I guess it will improve.
As a side note, ‘child containers’ is not a unique feature of Unity … Castle Windsor (it’s inner MicroKernel actually) has had this possibility for a long time.
Thanks for your tip Steve. Didn’t know that child containers are a feature of Windsor. I noticed that you prefer Windsor, lets say that I have the same opinion.
I noticed that the Unity team changed the implementation of the LifeStyleManager, they now allow custom lifestyles (In this weeks build). Lets hope they find away to make injection configurable. The attributes are a result of using ObjectBuilder under the hood.
Iam a starter of Unity Framework I Want to know more about Unity Framework where can I find in Online?