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

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:

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:

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

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:

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

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

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:

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

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:

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

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.

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:

The main reason was that I was deadmarching to meet one important deadline for couple of weeks and didn’t have time to finish entry application team was supposed to provide in order to compete..
I’m really sorry to miss that because I’m sure that was A LOT of fun
I don’t know id WYW would be next year, but in case it does I am taking vacation on time for that 🙂