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.
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 …
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:
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.
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:
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:
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!