Unity and injection with factories.

Last week in the office I just found a bug on how I was implementing a series of Inversion of Control chain using Microsoft Unity. To be precise, the bug has been found by one of the new guy in the team, Gary McLean Hall, the author of the book “APRESS – Pro WPF and Silverlight MVVM”.

Before starting with the explanation of the problem, let’s see what I am talking about. I believe that anyone of you know already concepts like “Inversion of Control” and ‘Dependency Injection”; if you don’t, just follow the links. Winking smile

A classic injection mechanism.

A classic mechanism of IoC is the one used by the Unit of Work and Repository patterns, where a repository can’t exist without an injected unit of work able to control the transaction. So, in order to have such a kind of example, I have implemented a simple data layer that shows you these dependencies:


Now, for these two contracts we will need to concrete implementations like the following classes:


And the final touch will be the implementation. Now, I am not going to implement a full data layer in this post as it is not the target of this writing, instead I want to show you how to “inject” a unit of work …

Repository constructor
  1. using System;
  2. using System.Linq;
  4. namespace InversionOfControl_dynamic
  5. {
  6.     public sealed class Repository : IRepository
  7.     {
  8.         #region IRepository Members
  10.         public void Create<T>(T entity)
  11.         {
  12.             this.unitOfWork.MarkNew(entity);
  13.         }
  15.         /// IRepository implementation removed to save space …
  17.         #endregion
  19.         #region Injection of the Unit of Work
  21.         private IUnitOfWork unitOfWork;
  23.         public Repository(IUnitOfWork unitOfWork)
  24.         {
  25.             this.unitOfWork = unitOfWork;
  26.         }
  28.         #endregion
  30.     }
  31. }

Now we can easily register the components with Unity and verify that when we call a Repository class, we are injecting a new Unit of Work using Unity.

The following test is accomplishing this task:

TDD the injection process
  1. [TestFixture]
  2. public sealed class StandardFixture
  3. {
  4.     private IUnityContainer container;
  6.     [TestFixtureSetUp]
  7.     public void InitializeTests()
  8.     {
  9.         container = new UnityContainer();
  10.         container.RegisterType<IUnitOfWork, UnitOfWork>();
  11.         container.RegisterType<IRepository, Repository>();
  12.     }
  14.     [Test]
  15.     public void Assert_That_Unity_Can_Resolve_Dependency()
  16.     {
  17.         IRepository repository = container.Resolve<IRepository>();
  18.         Assert.That(repository, Is.Not.Null);
  19.         Assert.That(repository, Is.InstanceOf<Repository>());
  20.         // Here I have created a public read-only property
  21.         // for testing purposes
  22.         Assert.That(repository, Has.Property(“UnitOfWork”).Not.Null);
  23.     }
  24. }

So far so good. The only missing part here is the last statement (line 22) of the code. Here I have created a read-only IUnitOfWork property, only in the concrete Repository class, in order to test that the IUnitOfWork is injected properly.

Injecting using factory

Now, let’s assume for a second that the previous approach is not valid; it is not valid because we are not in charge of creating an IUnitOfWork by our self. We need a factory that will create the contract for use.

So, first of all, I am going to create a simple factory that will return, with a static method, an instance of an IUnitOfWork object.

Unit of Work Factory
  1. public sealed class Factory
  2. {
  3.     public static IUnitOfWork GetUnitOfWork()
  4.     {
  5.         return new UnitOfWork();
  6.     }
  7. }

Now we are screwed because the previous approach does not work anymore… Green with envy If I want to create a new instance of a repository I need to inform Unity, somehow, that it needs to call this method of the factory to create a new instance of an IUnitOfWork. But how?

We found the class InjectionFactory ables to specify a delegate for the creation of a new object, like this code:

InjectionFactory declaration
  1. container = new UnityContainer();
  2. container.RegisterType<IUnitOfWork>(new InjectionFactory(c =>
  3.     Factory.GetUnitOfWork()));
  4. container.RegisterType<IRepository, Repository>();

Now we can simply assert that when we create two instance of an IRepository interface using Unity, it will return two different instances of the IUnitOfWork object:

Code Snippet
  1. [Test]
  2. public void Assert_That_Unity_Can_Resolve_Dependency()
  3. {
  4.     var currentRepository = container.Resolve<IRepository>();
  5.     var currentUoW = currentRepository.GetType().GetProperty(“UnitOfWork”).GetValue(currentRepository, null);
  7.     var expectedRepository = container.Resolve<IRepository>();
  8.     var expectedUoW = currentRepository.GetType().GetProperty(“UnitOfWork”).GetValue(expectedRepository, null);
  10.     Assert.That(currentUoW, Is.Not.Null);
  11.     Assert.That(expectedUoW, Is.Not.Null);
  13.     Assert.That(currentUoW, Is.Not.EqualTo(expectedUoW));
  14. }

If you want to read more about this object and other way of customizing the way Unity allows you to register objects, you can have a look at this section of MSDN:

Happy IoC to everybody!

Open-mouthed smile