Introduction

With its latest release, the Enterprise Library from Microsoft introduces a new component named Unity. This application block provides an easy path to implement the IoC pattern, and consequently the Dependency Injection pattern.

All the references for the Enterprise Library documentation can be found at the end of the article.

Background

Inversion of Control and Dependency Injection are the key points to understand how Unity works and the benefits of including it in our projects. If you want a deep dive on these patterns: http://martinfowler.com/articles/injection.html.

The scope of this article is writing code that is loosely coupled. Let's examine the following DummyLogger class:

publicclass DummyLogger
{
private IWriter _selectedWriter;
public DummyLogger()
{
//The container class is in charge for the initialization of the interface.
//the result is a strong dependency between the two objects
_selectedWriter = new ConsoleWriter();
}
publicvoid WriteOutput(string msg)
{
_selectedWriter.Write(msg);
}
}

The first thing that comes to mind to break the relationship between the two objects is to delegate the creation of the class member to someone else:

Nothing new until now. This can be interpreted as a trivial implementation of the IoC pattern. The contained object is no more controlled by its container class.

But what if we don't care about the real implementation of the IWriter interface ? Here's where Unity and Dependency Injection comes. The concrete implementation of the class member will be "injected" by Unity depending on its configuration. The first thing we need to do is expose the class/interface with its get/set methods and mark it with the [Dependency] attribute to make it visible to the application block.

Behind the scenes, each class/interface decorated with the [Dependency] attribute will be created according to the Unity container's configuration. This can be done programmatically or via the .config file.

Points of interest

Design patterns are without doubt a very interesting argument. With Unity, we are able to implement two of them in a very easy way. Dependency Injection allows us to create code that is decoupled, where we can create dependencies without hard-coding anything on our project.

I approched and start to read about IoC and DI when i discovered Unity and i agree that the more an example is basic and simple the more easy is for a novice to get the concepts of the argument.Thanks !