.NET and me Coding dreams since 1998!

18May/084

Design for testability – Microsoft Unity (part 7)

On my quest to design for testability, I've already covered:

(In case you don't know what IoC containers are, I advise you to take a peek at Part 4 of this series first before continuing  with this article)

Microsoft Unity in general

Today's post would be covering how IoC looks like in case of Microsoft Unity, which is developed and maintained by Microsoft Patterns and practices team. Microsoft Unity is currently in version 1.1 and it can be downloaded as part of Enterprise Library 4.0 or as a separate download.

Being Microsoft IoC tool, (beside "evil empire" prefix thing) Unity got an excellent documentation and vibrant CodePlex web site with discussion thread where all the answers can be found. IMHO, Unity is the best documented IoC tool which is the most important reason why I prefer to use it

Like StructureMap, Unity is IoC framework only without any additional DAL and UI parts we can find in Spring and Castle Project. It's size is 140 Kb only (70 Kb unity+70 Kb ObjectBuilder2) so it is very lightweight in both senses.

On similar way Windsor builds on top of MicroKernel, Microsoft Unity IoC is built on top of new ObjectBuilder2 which was rewritten to tackle three major issues original ObjectBuilder had:

  • Attribute only interception model without the option of manual code service locator approach (the only way to work with ObjectBuilder was to decorate members getting DI with special attributes [CreateNew] and [Dependency])
  • lack of configuration based approach where in configuration file container components and services are declared.

Unity now fully supports angle bracket configuration mode and "no configuration" mode (with or without using attribute magic) and this blog post would present both ways of using Unity.

Code solution overview

In this example (as in two previous ones) I am starting where the Part 3  ended - with a solution based on manually implemented setter type of dependency injection with internal setters exposed to test assembly. The solution I would end is the same code as the one in StructureMap post   and Windsor post where all of the internals would be removed and manual dependency injection (DI) would be replaced with service locator (SL) usage. SL would be used in this post also in opaque manner like in previous posts.

My main goal with the end state solution of this blog post is to have as similar as possible end code with the code in previous examples so you could compare the solutions.

Note: Although used in this examples,  using opaque dependencies is not good practice, so please check out my next post in this series where I would present in detail how this example would look using transparent IoC dependency injection style which is the way I prefer. The only reason why I am using opaque dependencies in my previous posts is that I found out explaining IoC concepts to people new to it an uphill battle as soon I show constructor accepting all this interfaces as parameters. So, in this posts I do the same thing I do in reality: selling first SL, DI and IoC on a way easier to sell and the once that is done I am introducing transparent DI, AMC (auto mocking container) etc

Using Microsoft Unity with configuration file

Facade.ServiceLocator

Before proceeding to the example itself, I would do first the same thing I did in castle example: build a separate Facade assembly which would expose ServiceLocator singleton and encapsulate usage of Unity block. The two main reasons why I want to do that are:

  • making code using IoC ignorant on what exact Framework is used and
  • to achieve singleton nature of unity container

So, mentioned Facade class library and ServiceLocator static type in this example would look like this

image

with very simple implementation based on delegating calls to Unity

using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Facade
{
    public static class ServiceLocator
    {
        private static readonly UnityContainer _unityContainer;

        static ServiceLocator()
        {
            _unityContainer = new UnityContainer();
            UnityConfigurationSection section= 
                (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
            section.Containers.Default.Configure(_unityContainer);            
        }


        public static T Retrieve<T>()
        {
            return _unityContainer.Resolve<T>;();
        }

        public static T Retrieve<T>(string key)
        {
            return _unityContainer.Resolve<T>(key);
        }
    }
}

As you can see from the code above ServiceLocator functionality requires adding a reference to three additional assemblies:

image

 

 

  • Microsoft.Practices.Unity  - Contains UnityContainer definition
  • Microsoft.Practices.Unity.Configuration - Contains the UnityConfigurationSection definition
  • System.configuration - Contains the ConfigurationManager type using for manipulating configuration files

In static constructor of the ServiceLocator type there is Unity IoC container initialization, readout of the Unity configuration section from configuration file and initialization of container based on the mappings defined in configuration file.

Configuration file

Configuration file is very simple (at least for this example where we have single container with only 2 singleton components) and it looks something like this:

  <?xml version="1.0" encoding="utf-8" ?>
  <configuration>
		<configSections>
		  <section name="unity"
				type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,							Microsoft.Practices.Unity.Configuration, Version=1.1.0.0,
	  			Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  		</configSections>
		<unity>
			<typeAliases>
				<!-- Lifetime manager types -->
				<typeAlias alias="singleton"
				  type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
				  Microsoft.Practices.Unity" />
			</typeAliases>
			<containers>
				<container>
					<types>
						<!-- Lifetime managers specified using the type aliases -->
						<type type= "Example.UserManager.IUserManager, UserManager"
							mapTo="Example.UserManager.UserManager, UserManager">
							<lifetime type="singleton" />
						</type>
						<type type= "Example.UserManager.IUserProvider, UserManager"
							mapTo="Example.UserManager.UserProvider, UserManager">
							<lifetime type="singleton" />
						</type>
  					</types>
				</container>
			</containers>
		</unity>
  </configuration>

Pretty self-explanatory  configuration file so I would just highlight here that in it:

  • I defined unity configuration section (notice that the section name is the same one used in constructor code snippet above)
  • In Unity configuration section I defined an alias for singleton container life time manager (which usage is optional but because it makes shorter type lifetime definition I think it is good practice to be used)
  • I defined then in default container singleton mappings (using the defined alias) of the type (interface in this example) and mapTo (type implementing interface)

Another thing deserving brief mentioning here is that my example uses app.config but beside app.config and web.config Unity supports custom configuration files in case you want to keep Unity configuration separated from your main configuration data. (Check out the Unity help file for copy/paste how to code example)

Consuming services

Now, when we saw how Unity IoC is getting populated with appropriate components consuming of those components is very easy. Let's check out how Driver console project would look like in this case:

using System;
using Example.UserManager;
using Facade;

namespace Driver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IUserManager _userManager = ServiceLocator.Retrieve<UserManager>);
            int activeUserCount = _userManager.NumberOfUsersActiveInLast10Days("M");
            Console.WriteLine(activeUserCount);

            Console.ReadKey();
        }
    }
}

Yeah, I said it is very simple... :) All we need to do is to Use ServiceLocator.Retrieve method and pass it as Generic parameter service interface of the component we want to retrieve and that would result with Unity returning instance of the type mapped to that interface in app.config. After that code logic uses that instance on the same way how it would use it if there were no IoC.

(For brevity of blog post I would skip the Provider related IoC code. In case you care, check out the code sample which you can get using the link on the bottom of this post

Attribute magic

If you check out the code of UserManager in configuration example just described you would see next code

        private IUserProvider _userProvider;

        public IUserProvider Provider
        {
            get
            {
                if (_userProvider==null)
                    _userProvider=ServiceLocator.Retrieve<UserProvider>);
                return _userProvider;
            }
            set { _userProvider = value;}
        }

The code inside the UserManager is referring that Provider property which then perform lazy retrieval from ServiceLocator of UserProvider type on opaque SL usage way.

        public int NumberOfUsersActiveInLast10Days(string userName)
        {
            IList<User> userCollection= Provider.GetUserCollection(userName);

            int result = 0;
            foreach (User user in userCollection)
            {
                if (user.LastActivity > DateTime.Now.AddDays(-10))
                    result++;
            }
            return result;
        }

Unity gives as an option (not necessary to use) of decorating type members in need of injection with [Dependency] attribute and then Unity do all the plumbing for us. In our little example Provider property would get dependency injection automatically by replacing the Provider code above with something simple as this:

        [Microsoft.Practices.Unity.Dependency]
        public IUserProvider Provider { get; set;}

When Unity container creates instance of UserManager it would scan all of the public members searching for the ones decorated with appropriate attributes and  for each one found appropriate component would be retrieved in IoC container for service equal to member type.

In the concrete case above, when constructing UserManager, Unity would detect DependencyAttribute on provider property, it would search for component implementing the IUserProvider and it would set the property value to retrieved component instance.

Container BuildUp

The whole concept above is based on presumption that UserManager instance would be "constructed" by UnityContainer which during that construction would perform injection of IUserProvider dependency  property.

But in some scenarios we have already constructed UserManager instance without using of the UnityContainer (good old userManager=new UserManager()) and we would still like to set all of the properties marked with Dependency attribute with the container components.

To achieve that, we would add to ServiceLocator type BuildUp method which would encapsulate and delegate to Unity BuildUp method

        public static T BuildUp<T>(T instance)
        {
            return _unityContainer.BuildUp(instance);
        }

All we need to do here is to pass instance of the object containing members decorated with DependencyAttribute and UnityContainer would inject appropriate values (that would be Provider property in this example)

The way to use the build this method is as simple as the method itself. If we would take a look at Main method of Driver.Program type we would see something like this

            // using the build up method
            IUserManager _instanceUserManager = new UserManager();
            _instanceUserManager = ServiceLocator.BuildUp(_instanceUserManager);
            activeUserCount = _instanceUserManager.NumberOfUsersActiveInLast10Days("M");
            Console.WriteLine(activeUserCount);

So, as we see here is instance of UserManager constructed without the using of Unity container and therefore I had to add next line in order to perform manual dependency by calling BuildUp method with instance of user manager passed as parameter.

That would result with Provider property being initialized with a UserProvider instance retrieved from IoC Unity container, in other words the end result would be the same as when we retrieve instance from IoC container.

The purists way of doing dependency injection

Although I personally don't see anything wrong in referencing the Unity assembly in assemblies containing domain/business objects due to its lightweight nature, there is a part of .NET community containing a lot of .NET rock stars not thinking like that (as Roy mention it here). Their biggest concern is that by using DependencyAttribute "infrastructure is leaking to domain space".

To tackle that purist separation concerns, Unity offers a way to achieve the same auto injection functionality without the usage of DependencyAttribute.

In short, to achieve this dependency injection constructor type of dependency injection has to be used which means that the type being injected (UserManager) has to define constructor accepting parameter of Service type (IUserProvider). Unity would then during the UserManager constructor check if any of the constructor parameters is contained in UnityContainer and if it is appropriate value would be injected.

So, after I removed the reference to Microsft.Unity itself from UserManager assembly I have to transform the Provider property to become constructor parameter:

        private readonly IUserProvider _provider;
        public UserManager(IUserProvider provider)
        {
            _provider = provider;            
        }

And that's all in this example where we have single constructor. In case we would have multiple constructors, Unity would use the one accepting the most parameters by default. Only in case that we would have multiple constructors and we would need from Unity not to use the greediest  constructor, we would need to decorate that constructor with [InjectionConstructor]  but IMO this is enough corner case to be discarded and Unity can be evaluated as the IoC framework not violating the SoC principle.

Using Microsoft Unity without configuration file

First of all, I won't repeat all of the thing mentioned already so no reason to panic :-). All of the mentioned things related to how the component is retrieved (attribute decoration, build up, ctor injection etc) stays exactly the same and only the way how container is getting populated is changing because in this example there won't be any configuration file.

This is the way I prefer to do IoC container build up mainly because of two reasons:

  • I prefer c# in favor of xml
  • I don't need to copy XML file to other assemblies (test one primarily)

So, I'll remove the configuration file and as a side effect of that the references to Microsoft.Practices.Unity.Configuration and System.configuration can be removed.

Facade.ServiceLocator modifications

I would also add to ServiceLocator type (beside the existing retreive method):

  • Register method which would accept as generic parameters types service interface and component type
  • InjectStub method which would accept as method parameter already instantiated type instance and which I plan to use in tests to inject the object mock to IoC container on similar way StructureMap does that

ServiceLocator would look like this:

using Microsoft.Practices.Unity;

namespace Facade
{
    public static class ServiceLocator
    {
        private static readonly UnityContainer _unityContainer = new UnityContainer();

        public static void Register<I, T>() where T : I
        {
            _unityContainer.RegisterType<I, T>(new ContainerControlledLifetimeManager());
        }
   
        public static void InjectStub<I>(I instance)
        {
            _unityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager());
        }

        public static T Retrieve<T>()
        {
            return _unityContainer.Resolve<T>();
        }
    }
}

Nothing special here: Register method delegates it's functionality to RegisterType unity container method and InjectStub delegates it's functionality to RegisterInstance method.

The only interesting thing here is the ContainerControlledLifetimeManager instance passed as parameter. Not to go too deep, but if you register type with default constructor on every retrieval Unity would return you new instance. To achieve parity with the configuration file part of the post I needed singleton behavior so I passed as a parameter LifetimeManager which makes sure that the type would be instantiated once per container life time which is effectively the singleton behavior I needed. Another interesting thing to note here is that this type is defined in ObjectBuilder2 assembly so add that to the Facade project references

Introducing Builder class

IMHO, building up the IoC container deserves separate entity which I usually call Builder so in this example Builder class would look something like this:

namespace Driver
{
    public static class Builder
    {
           public static void Init()
           {
               ServiceLocator.Register<IUserManager, UserManager>();
               ServiceLocator.Register<IUserProvider, UserProvider>();
           }
    }
}

So, the builder class effectively replaced the app.config file role defining mappings between services and components in UnityContainer

(Note: In this example, my builder class belongs to Driver application project which is not something I would do always in real world where I would usually prefer to utilize separate interface design pattern (there would be separate post on that too) and have separate assembly containing the Builder type)

Consuming services

Once builder code is in place Driver.Program class would be modified just to call Builder.Init() method before any code would be executed so any code in need of IoC components would retrieve it component

 

using System;
using Example.UserManager;
using Facade;

namespace Driver
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Builder.Init();

            IUserManager _userManager = ServiceLocator.Retrieve<IUserManager>();
            int activeUserCount = _userManager.NumberOfUsersActiveInLast10Days("M");
            Console.WriteLine(activeUserCount);

            Console.ReadKey();
        }
    }
}

Yes, it is simple as that.

How to write unit tests with Microsoft Unity?

In my preferred case of having Builder driving the configuration and not the xml configuration file it is very easy. All I need to do is to inject into IoC Unity container mocked instances which would be then used by tested code.

Check out the test:

        [Test]
        public void GetActiveUsers_TestCaseOfZeroUsers()
        {
            using (mockRepository.Record())
            {
                IUserProvider userProvider = mockRepository.DynamicMock<IUserProvider>();
                Expect.Call(userProvider.GetUserCollection(null))
                    .IgnoreArguments()
                    .Return(new List<User>());
                // injecting to UnityContainer mocked provider instance 
                ServiceLocator.InjectStub(userProvider);
                
            }
            using (mockRepository.Playback()) 
            {
                IUserManager _userManager = new UserManager();
                int count = _userManager.NumberOfUsersActiveInLast10Days("M");
                Assert.IsTrue(count == 0);
            }
        }

 

The only thing to notice here is how using the ServiceLocator.InjectStub method mocked instance is been registered in UnityContainer for purposes of this test execution.

All you need to do is to fill up the container with appropriate mocks/stubs/fakes and run the test

(Note: The test style described here is the one used in case of opaque dependencies which is not something I recommend as best practice. Mu next blog post would show the slightly different way how I write tests while using opaque injection style so be sure to check that out too)

What's next?

Purpose of this DFT blog posts is just to give a How-To quick start on Microsoft Unity so to get more information's on Unity I recommend checking next links:

Source code of the examples (config, attribute, buildup, purist, noconfig) presented in this post can be found here

 

Filed under: Uncategorized 4 Comments