Unity and injection with factories. | Raffaeu’s blog

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;
  3. namespace InversionOfControl_dynamic
  4. {
  5.     public sealed class Repository : IRepository
  6.     {
  7.         #region IRepository Members
  8.         public void Create<T>(T entity)
  9.         {
  10.             this.unitOfWork.MarkNew(entity);
  11.         }
  12.         /// IRepository implementation removed to save space …
  13.         #endregion
  14.         #region Injection of the Unit of Work
  15.         private IUnitOfWork unitOfWork;
  16.         public Repository(IUnitOfWork unitOfWork)
  17.         {
  18.             this.unitOfWork = unitOfWork;
  19.         }
  20.         #endregion
  21.     }
  22. }

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;
  5.     [TestFixtureSetUp]
  6.     public void InitializeTests()
  7.     {
  8.         container = new UnityContainer();
  9.         container.RegisterType<IUnitOfWork, UnitOfWork>();
  10.         container.RegisterType<IRepository, Repository>();
  11.     }
  12.     [Test]
  13.     public void Assert_That_Unity_Can_Resolve_Dependency()
  14.     {
  15.         IRepository repository = container.Resolve<IRepository>();
  16.         Assert.That(repository, Is.Not.Null);
  17.         Assert.That(repository, Is.InstanceOf<Repository>());
  18.         // Here I have created a public read-only property
  19.         // for testing purposes
  20.         Assert.That(repository, Has.Property(“UnitOfWork”).Not.Null);
  21.     }
  22. }

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…  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);
  6.     var expectedRepository = container.Resolve<IRepository>();
  7.     var expectedUoW = currentRepository.GetType().GetProperty(“UnitOfWork”).GetValue(expectedRepository, null);
  8.     Assert.That(currentUoW, Is.Not.Null);
  9.     Assert.That(expectedUoW, Is.Not.Null);
  10.     Assert.That(currentUoW, Is.Not.EqualTo(expectedUoW));
  11. }

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:

  • Microsoft Unity 2.0 documentation
  • InjectionFactory class

Happy IoC to everybody!

Leave a comment

Your email address will not be published. Required fields are marked *