Reusable decorators in F#


Comp-os-ition

F# fanbois often talk about how F# supposedly makes “composition” easier than C# (or indeed any OO-first langage). If you come from a C# background, you might not really think about what people mean by “composition”, because to be honest functional composition in the OO world is pretty difficult to achieve. You achieve it normally through inheritiance, which is a bit of a cop-out, or you start looking at things like like the Strategy pattern to achieve it in a more decoupled manner, typically through interfaces. But I tended to think of composition as something abstract before I started looking at F#.

One simpler way to achieve composition in the OO world is to use a (somewhat underused and misunderstood) feature common to IoC containers – to apply interceptors & policies to implement composition and pipelining (e.g. Decorator and Chain of Responsibility patterns). This is commonly known as Aspect Oriented Programming (AOP); common aspects include cross cutting concerns like logging and caching. Well, here’s an implementation of a fairly simple interception framework in F# that can chain up arbritrary decorators on a target function quickly and easily.

Composition through Aspects in F#

The goal would be to have a function – let’s say one that adds two numbers together – and be able to apply validation or logging to it in a decoupled manner.

First thing we do is define the signature of any “aspect”: –

Very simple – every aspect takes in a value of the same type as the “real” function, and returns a message that says either “fine, carry on, “something is wrong, here’s an exception”,  or “return prematurely with this value”. Easy. Let’s take our usual friendly calculator add function and a set of sample aspects: –

How do we chain these aspects up together with the raw add function? Quite easily as it turns out, with two simple functions, plus F#’s built-in compose operator (>>). The first one “bolts” one aspect to another, and returns a function with the same signature. The second function closes the chain and bolts the final aspect to the “real” function: –

Now that we’ve done that, we can chain up our aspects together using the following syntax: –

Nice, but we can make it better by defining a couple of custom operators which allows us to write code much more succinctly: –

Conclusion

This sort of compositional frameworkl is relatively easy on the eye, and thanks to F#’s ability to generalise functions automatically, aspects are generic enough to achieve decent reuse without the need for reflection or codegen. Whilst this isn’t a replacement for everything that you can do with a framework like Unity, Ninject or Postsharp, this very simple example illustrates how you can rapidly compose functions together in a succinct manner. If you’re interested in more of this sort of thing, have a look at Railway Oriented Programming on the excellent F# for Fun and Profit website.

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

Getting creative with IDisposable Part 2


In my last post, I gave some examples of how we can use the IDisposable interface in conjunction with the using statement to implement an on/off pattern wrapping around some critical region of code, even though there is no “disposable resource” involved.

Problems with using IDisposable

In this post I want to expand on the previous examples to illustrate a more general solution to that problem. In the previous post, all the examples implemented IDisposable directly in order to participate in the using statement. However, there are reasons why you might not wish to have this coupling: –

  1. Having a type implement IDisposable that has nothing to do with reclaiming of resources is somewhat misleading e.g. changing the console colour or the cursor icon. This is not what IDisposable was created for and can lead to confusion.
  2. We may not always want to call the “on” action on construction of the object; perhaps we want to use it in other scenarios.
  3. Compile-time tools such as Code Analysis and Coderush etc. may complain if you do not implement IDisposable in the “proper” way (with the Boolean overload) etc.

ISwitchable

There’s a way around this by making a new interface which I call ISwitchable, which is implemented by any classes that we want to use within the Using statement yet don’t want to implement IDisposable on (for the reasons outlined above).

image

Obviously, when we call “On” we’ll do the “on construction” action, and “off” will do the equivalent of the “Dispose()” call.

    The DisposableAdapter

So, how do we use ISwitchable within the context of the Using statement? Well, we can’t directly – obviously the using statement only works with IDisposable – so we use the Adapter pattern. This pattern shows how we can “massage” an object implementing one interface into another interface – in our case, from ISwitchable to IDisposable. We therefore create an adapter class which takes in an object that is of type ISwitchable and adapts it to work with IDisposable: –

ClassDiagram1

And here’s a (cut-down) version of the code for the adapter. All it does it delegate calls from the constructor to On, and Dispose to Off: –

image

Then we use it as follows, with the results below: –

image

  • CodeTimer simply starts a Stopwatch on On, and stops it (and outputs the time) when Off is called.
  • ConsoleColourInverter swaps the foreground and background console colours whenever On and Off are called.

image

So, we get two of these switchable “behaviours” applied onto our code; they start automatically, and then remove themselves once the using statement goes out of scope (as can be seen by the timer finishing and the console colour resetting itself). We don’t have to worry about exceptions either in the sense that because this is in a using statement, the finally block will automatically call dispose on both DisposableAdapter instances, which in turn delegate to the ISwitchable’s Off() method.

Conclusion

This is kind of reminiscent of aspect-oriented programming i.e. we’re applying a set of behaviours around some code and letting them do the work without us getting involved. Through the use of the Adapter pattern we have completely decoupled ourselves from IDispose, and with some use of generics are able to use these switchable objects within the context of a using statement pretty succinctly.

Getting creative with IDisposable Part 1


It occurred to me it might be interesting to describe some of the more unconventional uses of IDisposable that can help to make your code more readable, and even apply a kind of AOP-style coding to your code. MSDN describes IDisposable as follows: –

Defines a method to release allocated resources.

In the remarks section it states this: –

The primary use of this interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it is not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and stream

However, there is a secondary use for this interface which has absolutely nothing to do with the GC or memory allocation etc.. It comes into being because of the way that the “using” statement works in C#, which behind the scenes, simply calls Dispose() for us once the using statement goes out of scope (in a finally block). We can use this to our advantage in a number of situations where you want have the following behaviour: –

  1. Turn on something
  2. Do some code utilising that something
  3. Turn it off again
    Consider the following (contrived) example – we’re in a dark room and want to write out some text on a keyboard; in order to do that we need to turn on the light whilst we’re typing, and then turn it off when we’re finished: –

image

 

image

A more elegant way might be as follows: –

image

This is a much more readable version of code; it’s implied from the using statement what the scope of the light is. All we have to do is implement IDisposable on our Light class, and on the constructor and Dispose call the appropriate methods (bear in mind that Dispose gets called automatically once the using statement goes out of scope).

image

Easy. There are many situations where this pattern could be applied that have nothing to do with managed resources: –

  • Temporarily changing the console colour and then having it go back to what it was
  • Changing the mouse pointer to an egg-timer whilst doing some time-consuming operation and when it completes resetting it
  • Starting a Stopwatch when an operation starts and stopping it when it completes
  • Changing some settings on your UI e.g. writeable / read-only etc. when in a particular application state etc.
    In short, anywhere that you want to “temporarily” set the state of something and then reset it again. You can also chain them up: –

image

Nice. In my second post, I’ll discuss a way of generalising this class of problem and how we can decouple ourselves from IDisposable yet still retain the benefits of the using statement.

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:

image

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

image_thumb[30]

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

image

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

image

And of course there’s the application successfully running!

AOP with Unity – Part 2


In my previous post I gave some examples of how Unity implements behaviours (or interceptors) typically using a form of the Decorator pattern. Most of the examples you see of where you use these behaviours are for classes you yourself own, and thus can put attributes on the methods or whatnot.

There is, however, another time where Unity’s behaviour / interceptor functionality is extremely useful, and that’s when you don’t have control over the class that you wish to decorate.

A good example of this is if, for example, you have a proxy WCF service reference in a client application. WCF will generate you a service class with all the methods from the WSDL file (and also generate the entities if you aren’t providing them yourself), and even generate an interface from that service class. However, it’s a generated file, subject to change at any time etc.. The interface is not partial and not really open for modification.

Caching a WCF service call

Let’s say that you want to implement some form of caching from your service proxy, so that if you call the same method twice, you don’t go back to the server the second time. Perhaps this is because the service method is static data or something. Yes, you could optionally provide a client-side class which caches the data manually, but now you’ve got two sources of data – one for static data and one for other “live” data. Wouldn’t it be nice if your service class offered caching for those methods that you want to cache data from, but not from the others?

In this case, the real problem is, of course, that the proxy class is generated so you can’t modify it at all – but this is when Unity comes in. Imagine the following proxy interface: –

image

The first three methods are typically reference data and shouldn’t be called more than once by the client application. The last two represent calls whose results are more dynamic and shouldn’t be cached.

Here’s a (mock) concrete implementation of the proxy. Remember, this code represents designer-generated code which we cannot modify: –

image

This mock class is set up so that the second call to any of the reference data methods throws an exception – obviously not exactly “real world” but it serves the purpose here to test if we will only certain methods more than once.

Here’s the code to simulate our client application: –

image

The Initialise method simply registers the ServiceProxy with the associated interface, and assigns it as a singleton – thus all calls to get IServiceProxy throughout the application would get the same proxy class.

The LoadSomeData method simply runs through the different methods and prints some data to the console.

Unsurprisingly, when we first run it, we get the following: –

image

So, how can we inject some caching into our proxy class without modifying it? That’ll be in my next post Smile