Unity Application Block 3.0 QuickStart

The Unity Application Block is a Dependency Injection Container programmed by the Microsoft patterns & practices group. Dependency Injection is a programming pattern to avoid tight coupling of classes and dependencies. A short explanation can be found in one of my blog posts or in an even better post from Martin Fowler.

After the downloading and installation of unity, all references in the project can be set. For this example it is enough to reference the assemblies Microsoft.Practices.Unity and Microsoft.Practices.Unity.Configuration.

Loose coupling starts with an interface as a contract. This interface is used to inject dependencies in classes. In the classes every call to a dependency will run against this interface.

This example is a little ToDo-Manager with the following model and a static class that works as a helper for the creation of ToDos.

1_ToDoManger

Furthermore the manager class has to work with a data store to create, read update or delete ToDos. This data store will be called data service in this example, because the class serves as a means to store data. This service is the dependency that will be injected later, so an interface is necessary and classes that implements this interface. The following image shows the scheme of the interface and the two classes which implement the interface. The class SqlDataService is the class that works with the SQL-Server for storing data, throughout the class MockDataService mocks access to a data store. This comes in handy if the ToDoManager will be tested during a unit test. In conclusion this means that the complete functionality of the ToDoManger can be tested independent of the SQL-Server. That is – in short words – the idea behind Dependency Injection. The injection will be done as a parameter in the constructor of the class.

public class ToDoManager
{
    IToDoDataService ds;
        
    public ToDoManager(IToDoDataService service)
    {
        ds = service;
    }
        
    public void AddNew(String subject, String description, DateTime dueAt)
    {
        ToDo todo = new ToDo()
        {
            ID = Guid.NewGuid(),
            Subject = subject,
            Description = description,
            DueAt = dueAt
        };

        ds.Crate(todo);
    }
}

This example shows only the idea behind it and not a real implementation, especially a boring data access layer is missing.

2_Interface

public interface IToDoDataService
{
    bool Crate(ToDo todo);

    ToDo Read(Guid id);

    bool Update(ToDo todo);

    bool Delete(ToDo todo);
}

public class ToDoDataService : IToDoDataService
{
    public bool Crate(ToDo todo)
    {
        // save to database
        return true;
    }

    public ToDo Read(Guid id)
    {
        // read from database
        return new ToDo() 
        { 
            ID = Guid.NewGuid(), 
            Subject = "Read", 
            DueAt = new DateTime(2013, 12, 10) 
        };
    }

    public bool Update(ToDo task)
    {
        // Update to database
        return true;
    }

    public bool Delete(ToDo task)
    {
        // Delete to database
        return true;
    }
}
public class ToDoMockService : IToDoDataService
{
    public bool Crate(ToDo todo)
    {
        // Mock
        return true;
    }

    public ToDo Read(Guid id)
    {
        // Mock
        return null;
    }

    public bool Update(ToDo todo)
    {
        // Mock
        return true;
    }

    public bool Delete(ToDo todo)
    {
        // Mock
        return true;
    }
}

The main purpose of Unity is now to resolve all dependencies automatically based on a configuration. The configuration can be set in the code of the program or as a .config file. The example uses a .config file as listed below.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity"
        type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
              Microsoft.Practices.Unity.Configuration" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <unity>
    <containers>
      <container>
        <types>
          <type
             type="UnityQuickStart.ServiceInterfaces.IToDoDataService, UnityQuickStart"
             mapTo="UnityQuickStart.ServiceImplementations.ToDoDataService,
                      UnityQuickStart" />
        </types>
      </container>
    </containers>
  </unity>
</configuration>

The configuration forces Unity to use an instance of the ToDoDataService class every time the IDataService interface is used. This means also that another configuration forces the use of the MockDataService. Unity resolves the dependencies with a simple call of the method Resolve().

static void Main(string[] args)
{
    ToDoManager toDoManger = DIContainer.Container.Resolve<ToDoManager>();

    toDoManger.AddNew("Test", "Test description", DateTime.Now);
}

The access to unity in this example is wrapped in a static class called DIContainer for Dependency Injection.

public static class DIContainer
{
    public static IUnityContainer Container { get; private set; }

    static DIContainer()
    {
        Container = new UnityContainer()
            .LoadConfiguration();
    }
}

If everything works the debugger will show the correctly resolved instance of a class. In this case an instance of the SqlDataService class.

3_ItWorks

This post shows only a QuickStart of using Unity. Unity itself is a powerful Dependency Injection Container with a lot more features and possibilities. The installation also comes with several examples in C# and VB.NET

The example solution can be viewed or downloaded here:
https://docs.google.com/file/d/0B6O4K85kZHBybUVZUlhBMldOT2c/edit?usp=sharing

More examples of using Unity can be found here:
http://msdn.microsoft.com/en-us/library/vstudio/hh323691(v=vs.100).aspx
http://www.sidarok.com/web/blog/content/2008/05/15/a-basic-hands-on-introduction-to-unity-di-container.html
http://www.codeproject.com/Articles/33090/Using-the-Dependency-Injection-Pattern-and-Unity-C

Advertisements
This entry was posted in C#, Development and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s