Aspect Oriented Programming (AOP) is a way of addressing the ‘cross cutting concerns’ of a system – e.g. logging, security, transactions, caching etc. Using aspects you can apply these concerns without hand writing it into each place you need it. This helps with creating clean solutions and with testability. There’s a good summary of this in Clean Code – A handbook to agile Software Craftsmanship, so for more have a read of that (chapter called Systems)…
The system I’m building at the moment uses AOP to apply logging and caching. It’s remarkably simple to apply AOP using Castle Windsor (this is one of the reasons why I picked Castle Windsor as my container – it’s one of the most mature containers so a lot of features exist and have been well used). This post from Ayende was my starting point. The reason I didn’t use the code ‘as is’ is because I don’t want to configure my aspects in XML.
Aspects are applied using interceptors. Interceptors are given to us by Windsor and pretty much do what’s described by the name; they intercept method calls. Windsor achieves this by dynamically generating a proxy. Fortunately, all of this happens for us and we don’t really have to care (other than be aware of the implications a proxy has).
We can only intercept method calls we know about – that is all calls made on methods which implement those defined on the service interface. These services / implementations must be registered within our container.
Using a ‘facility’ we can get involved in the registration process and add our interceptors as required (by hooking up to the kernel ‘ComponentRegistered’ event). The facility creates an interceptor if the component being registered requires an aspect.
The interceptor which gets added runs all the aspects that are registered for that component. An aspect can decide to invoke the implementation or not depending on its vote options.
You can register aspects by calling the WithAspects extension method. This must be done before any components are registered with the container (at least any components which you would like your aspects applied to).
That’s pretty much it… The aspects I’ve written so far are Logging and Caching, I will blog about them shortly. Once I’ve done all the posts I’ll make the code available somewhere.