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: –

  1. 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).
  2. Turn on Interception in Unity by adding the Interception Extension.
  3. Set up a policy which applies that call handler under a given matching rule, in our case the CustomAttributeMatchingRule.
  4. 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: –

  1. Turn on the Interception extension – automatically done by Automapper if needed.
  2. Manually set up policies in Unity – automatically done as LoggingAttribute inherits from HandlerAttribute.
  3. Manually register IThing for policy injection – automatically done by Automapper because of the [PolicyInjection] attribute.

Much nicer Smile

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: –

  1. Create your call handler as normal.
  2. Ensure that it inherits from HandlerAttribute.
  3. Apply your Attribute as required.
  4. 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: –

image

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.

image

Finally, you then can retrieve them from Unity either individually by name, or all at once through the handy ResolveAll<T>() method: –

image

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 Smile

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.

image

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: –

image

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: –

image

Then, you can set up dependencies on other classes as follows: –

image

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.

image

image

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 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…

  1. Fire up Visual Studio and open your solution.
  2. Open NuGet on the project you wish to perform the Unity registrations on (typically this will be your startup project)
  3. Search for Unity Automapper. NuGet isn’t the best at finding packages so you might have to search for it a bit.
    image
  4. Alternatively you can simply install it via the Package Manager Console with the command.image
  5. That’s it! You’re now ready to start using the AutoMapper!

Usage

This is even easier.

  1. Add a using statement to the top of your source file where you want to perform the registration on.image
  2. Create your Unity Container as normal.
  3. 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: –image
  4. Alternatively you could just chuck in all the types in e.g. your executing assembly at run-time: –image
  5. 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: –image
  6. 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…

  1. 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).image
  2. 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.image

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!).