Archive
Unity Automapper in 10 minutes
If you have ten minutes (well, 12), and use the Microsoft Unity DI framework, take a look at the Unity Automapper. It removes the need to manually map interfaces to concretes, as well as offering powerful new features to enable plug-ins and easy-to-use AOP.
Make sure you watch in HD to actually see the code
Unity Call Handlers released on NuGet
Having worked on this for a while, I’ve now released a set of simple, easy-to-use call handlers for Unity on NuGet. These include Method Logging, Timing, Caching and null argument Validators. I might add to this collection in future – the source code is on GitHub so you have a look through it as you want (or submit some more if you like
). If you use it in conjunction with the Unity Automapper, it allows you to very, very easily start getting a pluggable set of classes going with aspects.
You can get the package on NuGet and have a look at the docs on GitHub.
Unity Automapper 1.3 released
A new version of the Unity Automapper (1.3) is now available on NuGet. It now supports a fluent-style, provider API in addition to the attribute-based model for overriding default settings etc.
I’ve also decided to open-source the Unity Automapper at this time and push it onto GitHub. There are several reasons for this. Primarly, I’ve been using the public, web-facing version of TFS for a while but wanted to try GitHub out to see the differences both from a website as well as a source control mechanism perspective.
I plan on blogging shortly about my initial experiences of GitHub (generally quite positive) but for the purposes of the Unity Automapper, all documentation and guidance can now be found here. I still plan on publicising updates via this blog, but it will no longer be the repository for documentation and low-level details of each release.
Unity Automapper 1.2 released
Unity Automapper is probably nearly finished. There aren’t many features left that I want to implement without over-complicating things – which is one of the main goals I want to avoid. Things I am looking at include adding a mechanism to allow an assembly to provide configuration details rather than attributes placed directly on types, and possibly the ability to provide an explicit list of interfaces to map rather than a seek-out-all-interfaces approach. Version 1.2 contains a single feature which should make using AOP in Unity much, much easier in Unity: the [PolicyInjection] attribute. By marking this attribute on any interfaces, mappings automatically participate in Policy Injection using interface-based-interception. Confused? Read on.
The Problem with Interception
I’ve blogged about Unity Interceptors several times before, and how they can provide cleaner code for you etc. The biggest difficulties to adopting them that I’ve seen are: -
- Difficulty in understanding the interception pipeline and how AOP works.
- Difficulty in setting up interceptors or call handlers.
The first one can be overcome with an explanation of what AOP is, and some simple diagrams. The second is more problematic. Let’s assume we have a simple Call Handler that logs method entry and exit calls into the console that we want to apply via an attribute onto methods: -
public class LoggingCallHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
var methodName = input.MethodBase.Name;
Console.WriteLine("Entering method {0}", methodName);
var result = getNext()(input, getNext);
Console.WriteLine("Exiting method {0}", methodName);
return result;
}
}
To get this to work in Unity you have to do several steps: -
- Create an Attribute and apply it onto the method that you want the call handler to apply onto. (Note: You can use the TagAttribute instead of your own attribute, which is weakly-typed but doesn’t require you to create a custom attribute).
- Turn on Interception in Unity by adding the Interception Extension.
- Set up a policy which applies that call handler under a given matching rule, in our case the CustomAttributeMatchingRule.
- Register the actual interface mapping in Unity with two overrides: -
- Apply the PolicyInjection interception behaviour to tell Unity that this type takes part in Policy Injection
- Apply the Interface Interceptor to tell Unity to construct interface-based proxies rather than interitance-based proxies
public class LoggingAttribute : Attribute { }
public interface IThing { [Logging] void Foo(); }
var container = new UnityContainer();
//Turn on interception
container.AddNewExtension();
// Create a policy for this logging handler.
container
.Configure()
.AddPolicy("Logging")
.AddMatchingRule(new CustomerAttributeMatchingRule(typeof(LoggingAttribute), false))
.AddCallHandler();
//Set up IThing to participate in Policy Injection
container.RegisterType<IThing, Thing>(new InterceptionBehavior(),
new Interceptor());
Worse still, you would have to repeat the three policy lines for every call handler you used, and would have to explicitly provide those two overrides of every type registration in Unity. For someone who has never used interception, it’s a lot to take in.
Interceptor is by definition a more advanced topic but it allows many, many benefits, encouraging composition and reusability – so it should be as easy as possible to use. Many people I know aren’t even aware of the AOP side of Unity (or other IoC containers), or if they are, they’re scared off by it due to the difficulty of configuration.
Making Interception Easier
There are several stages that make interception easier with Unity. Let’s assume that your Call Handler is already created, as above. You want to apply that handler to a class using an attribute. It turns out that the easiest way to do that is to use the HandlerAttribute that comes built into Unity. So here our LoggingAttribute inherits from HandlerAttribute instead of the base Attribute: -
public class LoggingAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new LoggingCallHandler();
}
}
This special Attribute automatically does away with the need to explicitly set up a policy using the AttributeMatchingRule etc. – you simply apply it as required and Unity will automatically create a policy for you. To make life simpler, you can even have your call handler inherit from HandlerAttribute and return itself on the overridden call to CreateHandler, reducing the number of classes floating around.
The second part I mentioned earlier is the mapping of your client types in Unity that use the Call Handler: You normally need to register them for Policy Injection, but with the Automapper, you can now simply decorate your interface with the [PolicyInjection] attribute – this then automatically registers the type to be set up for policy injection. So the original source code sample which performs the Unity registration and policy creation above now looks like this: -
[PolicyInjection]
public interface IThing
{
[Logging]
void Foo();
}
var container = new UnityContainer();
container.AutomapAssemblies(Assembly.GetExecutingAssembly().FullName);
So no need to: -
- Turn on the Interception extension – automatically done by Automapper if needed.
- Manually set up policies in Unity – automatically done as LoggingAttribute inherits from HandlerAttribute.
- Manually register IThing for policy injection – automatically done by Automapper because of the [PolicyInjection] attribute.
Much nicer ![]()
Conclusion
The Unity Automapper, in conjunction with the in-built HandlerAttribute, makes it possible to create and apply call handler in a completely configuration-free manner: -
- Create your call handler as normal.
- Ensure that it inherits from HandlerAttribute.
- Apply your Attribute as required.
- Ensure that the interfaces that it is used on have the [PolicyInjection] attribute applied.
Unity Automapper 1.1 released
I’ve released a new version of my Unity Automapper today. It introduces what I’m finding to be a powerful feature of Unity that I call Multimapping which gives plug-in style capabilities in a very flexible manner.
Using Unity as an Collection Factory
Let’s say you had implemented a command pattern, and being a good developer you’d implemented your commands based on the ICommand interface: -
Now you want to write a command runner which iterates through all those commands. To register multiple items into Unity against the same interface, you need to give each registration a unique name and explicitly register each concrete manually. This also means tightly coupling the assembly that does the Unity registration to the one containing your commands.
Finally, you then can retrieve them from Unity either individually by name, or all at once through the handy ResolveAll<T>() method: -
But it’s still somewhat laborious to do the registrations manually. You have to pick names for each registration, then individually register them, and then explicitly call ResolveAll() to get them back – you can’t have the collection of them as a dependency. This is where the Automapper comes in ![]()
Unity Automapper Multimaps
Multimaps allow us to automatically register entire collections of concrete types against an individual interface, and then retrieve them extremely easily afterwards. Here’s the new features that allow us to do this.
Explicit Multimapping
You can now mark an interface as a Multimap. This tells the Automapper to seek out all implementations of that interface and to register them all against it.
That’s it. No need to explicitly register the Commands any more – just call RegisterAssemblies() or RegisterTypes() and they’ll get mapped to ICommand. You can now call the aforementioned ResolveAll() to get them all out.
Implicit Multimapping
Let’s say you always want this sort of behaviour, and don’t want to have to explicitly decorate your interfaces with the above attribute. There are now new overloads for the main entry points of the Automapper such as follows: -
MappingBehaviors help guide the behaviour of the mapper during auto-registration. In this case, we’ve told it to use Multimapping by default – so if we find more than one concrete type for any given interface, we’ll automatically use Multimapping behaviour. Otherwise, we fall back to standard behaviour. Of course, MappingBehaviors are flags, so you can mix and match any as you see fit.
Automatic Collection Registration
Thus far, if you want to get a handle to all of your multimap concretes, you have to get them via a call to ResolveAll(). With Automatic Collection Registration, you don’t even need to do that. This cool feature allows us to have dependencies that represent all the registrations against an interface simply by requesting an instance of IEnumerable<T>. First, perform mapping using the appropriate behaviour: -
Then, you can set up dependencies on other classes as follows: -
In this example, we are essentially telling Unity to pull out the mapping for the collection of all Commands. With Automatic Collection Registration, this is now possible – so you don’t have to explicitly call ResolveAll() any more!
Named Mappings
The default behaviour for multimapping is that each registration in Unity will be a named after the full name of the concrete type. If that’s not for you, you can also guide the mapper to pick a particular name for a concrete type by placing the MapAsAttribute on it.
Conclusion
Multimapping is a powerful feature that gives us the ability to easily have factories generating entire collections of objects. By using the two mapping behaviours illustrated above, you can do this without any attributes and without the need to resolve to otherwise needed explicit method calls in Unity.
It should be pointed out that multimapping is completely optional. This is a non-breaking change, so if you don’t need it and call the API without providing any behaviours etc., nothing will change.
Hope you enjoy it – I’ve tried to keep the API as simple as possible; let me know if you have any suggestions.
Using Unity Call Handlers to compose logic
The most common use of Unity Call Handlers (or Interceptors) is for cross-cutting concerns. I’ve demonstrated the use of such handlers in the past for things such as logging or caching. However, there’s another use for these handlers that allows us to build reusable blocks of business-related code that can be composed together to act in a number of ways: -
- Filtering out data that is not appropriate for the target method
- Enriching data before consumption by the target method
- Enriching the return data after consumption by the target method
Call Handlers as a pipeline
This is possible because of the way call handlers work – they form a pipeline whereby each handler has the opportunity to prematurely end the pipeline flow at any point, creating a return object, or amend the input argument before passing it on onto the next handler.
- The Blue lines indicate the initial flow from caller to target via each call handler.
- Any call handler may decide to prematurely return to the caller without passing onto the target, indicated by a red line.
- If the call makes it all the way to the target, it returns back up the stack to each handler, who cascades back up all the way to the source caller, shown in Green.
Filtering data with Call Handlers
Let’s start with a relatively simple example: a generic file parsing system which processes XML files dropped into folders. Each folder contains a different structure of XML file, and we have an appropriate parser class for each one. Perhaps we have ten different parsers. Now, let’s imagine that we wanted to filter out (i.e. not process) some files, for certain parsers – but not all of them – given some of the following conditions: -
- A file is too old – say, over a week old
- A file size is too big – say, over 10mb
- A file contains an attribute named “Ignore” on the root XML element
Now, if we were writing these parsers (with unit tests, of course), let’s pretend our IParser interface looked something like this: -
Imagine that each XDocument has a header that contains things like date published and size etc. etc. Also imagine that when each parser implemented ParseDocument it would first perform any tests required to ensure that certain filter conditions had not been failed. Remember, some parsers will not need to do any filtering. Some might need all three filters. Others might only need one or two.
Fragility of unit tests
Even if we abstracted the logic of these filters in helper methods – or even with interface on top of them so we could stub them out – it would still mean your unit tests for each parser growing with each extra filter that you add e.g. if you had a parser that had five filter conditions, you would have to mock out the first four in order to prove that the fifth was correctly checked. Even worse, if you decided to re-order your filter checks (let’s say that you realise that the first one is slow to run so push it to the back), your unit tests would break.
In the example above, to test that we are calling the second filter (IsDocumentTooLarge()) is being called, we have to mock the result of IsDocumentMarkedAsIgnore() first. If we swapped the order of the calls, our unit tests would break.
Using Call Handlers to act as filters
What I really want to see is code like this: -
Each of these attributes should map to a handler which performs a single check, and either passes on to the next item in the pipeline, or returns prematurely. Our unit tests on the parser would simply be ones that verify we have the attribute on the correct method, as well as tests for the actual parsing. That’s it.
Even better, as each call handler lives in its own class and is completely decoupled from any parser, we can easily apply them to other parsers very quickly and easily.
In my next post, I’ll demonstrate a simple call handler to perform one of these filters, and talk a bit more about the other two uses of CallHandlers that I mentioned at the start of this post.
Using Unity Automapper, Step-by-step
Although it’s pretty self-explanatory, I thought that some simple instructions how to use the Unity Automapper might be a good idea anyway.
Installation
If you’re reading this, there’s a good chance you’re coming here from the link in NuGet’s description, in which case you can skip straight to the Usage section below. Otherwise, read on…
- Fire up Visual Studio and open your solution.
- Open NuGet on the project you wish to perform the Unity registrations on (typically this will be your startup project)
- Search for Unity Automapper. NuGet isn’t the best at finding packages so you might have to search for it a bit.

- Alternatively you can simply install it via the Package Manager Console with the command.

- That’s it! You’re now ready to start using the AutoMapper!
Usage
This is even easier.
- Add a using statement to the top of your source file where you want to perform the registration on.

- Create your Unity Container as normal.
- If you have a list of types at compile-time that you wish to use as the source of registrations, simply call the AutomapTypes() method: -

- Alternatively you could just chuck in all the types in e.g. your executing assembly at run-time: -

- If, on the other hand you’re using a more plug-in style architecture where e.g. you want to source your registrations from assemblies that your registration project doesn’t have a reference to, or you want to map concretes that are internal to another assembly etc., you can just provide the assembly names using the AutomapAssemblies() method: -

- So in this example, perhaps we have an interface in our Services assembly e.g. IDataAccess, which is implemented by a class in DataAccess. You can now make the concrete implementation completely private; it’ll simply be found by the mapper and wired up.
That’s it! Either of those calls will perform any mappings that it can find into Unity; you’re now ready to go.
Other features
Here are a few other features that the mapper offers…
- If you want to make your data access layer a singleton in Unity, simply mark the interface (not the implementation!) with the [Singleton] attribute (this necessitates referencing the Automapper from that assembly as well).

- If you want to specifically ignore a type from the Automapper – perhaps you have a fake class you sometimes turn on or use in testing etc. rather than when really running – just mark it with the [DoNotMap] attribute.

That’s pretty much it. Two method calls and two (optional) attributes – not a massive API but hopefully one that saves you some time when using Unity.
Unity Automapper on NuGet
I wrote many, many moons ago about doing auto-mapping in Unity using e.g. reflection etc. instead of resorting to config files etc..
Well I’ve now released, via NuGet, a package that offers exactly that. It’s not the most configurable API but supports what I believe are the most common use-cases for auto registration, allowing you to get up and running in seconds. Just download the package, call a single extension method and off you go.
Features
-
Simple API exposed as extension methods on the Unity Container itself – up and running in seconds
-
Automatically registers multiple types based on interface implementations – no naming conventions required
-
Automatically registers types located across multiple assemblies – perfect for implementing DIP easily without breaking rules of encapsulation
So, if you use Unity, download the package and give it a go – I’d love to hear your feedback (good and bad!).
Unity’s [OptionalDependency] – don’t do it
Just a quick tip – when using Unity for DI – DON’T use the [OptionalDependency] attribute unless you absolutely have to.
Why? Because it can be incredibly unslow. I’ve not had a look at the source code so can’t know exactly, but as I recall, the way that Unity deals with OptionalDependencies when they are not available is by throwing an exception, which is then caught and supressed by itself.
Performance varies depending on the type of object and the number of constructors it has (among other things), but, for example, missing Strings that are marked optional are incredibly slow if not available – sometimes upto 50x slower to construct an object.
This might not be noticeable if you just create the odd object here and there – but if you start doing anything heavyweight, you’ll soon notice it – so avoid it wherever possible.
AOP with Unity – Part 3
So, here’s the final part of my Interception / Behaviours / AOP with Unity thread…
I discussed (at length) an example problem space we have in my previous post; I want to give an example solution which provides very good encapsulation to the client code using Interceptors.
Carrying right on then – we already have a layer of indirection from our concrete Service Proxy in the form of the IServiceProxy interface. So, we can use Unity to put a decorator class in between that and the “real” ServiceProxy. This middle class will delegate calls to the concrete service, and add the behaviour that we need.
Here’s the Interceptor class which will provide caching for our reference data methods. Notice it implements the IInterceptionBehaviour interface which Unity relies on:
Most of it is fairly simple: -
-
A collection of strings which represent method names whose data we will cache. A more robust implementation might be to use expressions instead of strings…
-
A couple of boiler-plate methods that the IInterceptionBehaviour interface needs but we don’t require.
-
A few static helper methods to aid readability
The crux of it is the Invoke method. This gets called when ANY method is called (or property is set/got) on the class we are decorating. We can then interrogate it and decide what to do. In our case, we’re checking if the method name exists in our black-list of method names.
-
If it doesn’t, we pass the call on to the real method.
-
If it does, and the data is already cached, we return that data instead.
-
If it’s not yet cached, we call the real method, cache the return value and then return the method data back out.
That’s the behaviour written – now we have to register it with Unity and against our type. Here’s the code that we need to change to have it work from a client perspective: -
The first line is a one-off call to the container to tell it to enable Interception within Unity. The Registration line has two new items added: -
-
An Interceptor<InterfaceInterceptor> that tells Unity how to implement interceptor (composition vs inheritance as discussed in my previous post)
-
The Behaviour that you want to implement – in my case, the Caching Behaviour that I have written
That’s it! We don’t change any client code – the cache happens completely transparently to the user of the proxy. When we now request the IServiceProxy, Unity will generate a decorator class for us and use that in front of the real service proxy. And just to prove it, here’s what it looks like at runtime: -
There’s the debugger which shows us Unity’s generated type (and how it stores a private field called target which points to the real object).
And of course there’s the application successfully running!

