SignalR with an IoC container


There seem to be a number of posts out there on how to use an SignalR with an IoC container e.g. MS Unity. Nearly all of them of them seem to be taking a sledgehammer approach to solve what most people generally want to do, which is create their Hubs with an IoC container. They generally don’t want to replace all of SignalR’s internal dependencies.

The easiest way to get dependencies injected into SignalR hubs is not by creating your own DefaultDependencyResolver – doing that will hand over control to you for creating not just Hubs, but basically all the different components within the SignalR pipeline. Worse still, for an IoC container like Unity which can create concretes that have not explicitly been registered, it can make life much more complicated.

A simpler approach is simply to register an implementation of the IHubActivator, as below: –

The HubActivator will get called only when SignalR needs to create a Hub specifically; you hand control over to your IoC container to create it, along with any of its dependencies. Much easier than the other approach, and easier to reason about.

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

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

image

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

image

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.

image

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

image

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.