Unity with config free AOP

At the current place of work i have managed to introduce the notion of IoC and DI. As the team was using EntLib i investigated Unity and found it to be a suitable replacement for Windsor or SM considering how we were going to be using it.
We have just started up a new project and i have asked one of the lads to investigate AOP with unity, what we found was a pretty simple solution for our initial requirement, logging the service calls using Unity

Below is the 3 files that make up the spike. it very trivial, but there is some pretty average info on how Unity work, there is sample (like this) but with little explanation as to what is going on. David Hayden is probably the first port of call for more info (note you will need to reference Unity 1.2 and Unity Interception).
Note we are using the TransparentProxyInterceptor not the InterfaceInterceptor, which i believe is broken as it does not handle inheritance, which in an OO world is not good enough.

class Program
{
static void Main(string[] args)
{
IUnityContainer container = new UnityContainer();
container.RegisterType();
container.AddNewExtension
<Interception>();
container.Configure
<Interception>().
SetDefaultInterceptorFor
<ITalker>(new TransparentProxyInterceptor()).
AddPolicy(“Logging”).
AddMatchingRule(new TypeMatchingRule(typeof(ITalker))).
AddCallHandler(typeof(LoggerHandler));

Console.WriteLine(“This is the start”);
container.Resolve<ITalker>().Talk();
Console.WriteLine(“This is the end”);
Console.ReadLine();
}
}

public interface ITalker
{
void Talk();
}

public class Talker : ITalker
{
public void Talk()
{
Console.WriteLine(“helllllllooooo!”);
}
}

public class LoggerHandler : ICallHandler
{
public LoggerHandler()
{
Order = 0;
}

public int Order { get; set; }

public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate
etNext)

{
Console.WriteLine(“** I’m in!**”);
var result = getNext().Invoke(input, getNext);
Console.WriteLine(“** Out I go 🙂 **”);
return result;
}
}
———————————————————
Which returns :
This is the start
** I’m in!**
helllllllooooo!
** Out I go 🙂 **
This is the end
———————————————————
*Sorry about the formatting, this is done with out WLW*

Unity – OMG… it just works!

I have started up at a new company back in Perth and am so far feeling pretty good about things. Initially I thought I may be back in “waterfall land”, but the guys are all super receptive to new ideas and very keen on moving to a more agile (or at least less waterfall) process.
The other dev’s and I have come up with a nice MVP/Presenter First framework with a repository pattern for the DAL and are currently using service with DTO‘s in the middle. All good so far.
Then I learnt we were using EF… ahhh ok…
Well, luckily the guys here have enough experience with it and have manged to put together a nice usable repository implementation using EF that is agnostic enough that any non EF should be able to come along and use it.. happy days.
Next step for me was to introduce IoC and AOP to the stack. These are somewhat new concepts here so I wasn’t to sure how they would go down. I have a wrapper Container that I use to abstract away all the container specific gunk and jargon that you can get with some containers. As we were very much in the EF/PnP/EntLib park here I thought I had better at least look into Unity to see if it is a viable option.
My last dealing with M$ IoC was ObjectBuilder in CAB… what a f&?king pig.
Needless to say I was not expecting anything special. I was however pleasantly surprised. Unity is supper usable and slotted in perfectly to my abstracted container adapter. If you are in a M$ centric software house I HIGHLY recommend trying out Unity. Far to many M$ devs don’t use IoC, often because there is a 3rd party framework that is not from M$ that is now required… the amount of time i have been told i can not use OSS on a project… grrr…well now there is no excuse. To see how painless it is checkout PnP guru David Hayden screencast and posts. Actually if you use any on the EntLib or PnP stuff you should be subscribed to DH blog; he is the ninja in this field and pragmatic enough to use (and have extensive knowledge of) other 3rd party frameworks such as the wonderful Castle stack.
Next step is to investigate the PnP AOP implementation namely the Policy Injection Application Block… will keep y’all posted

Gray hairs and coronaries …

Refactoring fundamentals of a rather large stack ca be daunting… I gave it a go over the weekend, modifying hundreds of files and tens of thousands of lines of code and, to be honest, I thought I had done a pretty good job doing so.
Monday morning comes around and there where some Small build issues (csproj.user are not in the a build outside of VS) but easily fix.
The really problem was when we started to do complex interactions… the app died…

Oh sh1t…. I’m fired..

Well maybe not fired just roll back to Friday and I have wasted a weekend.
Long story short… don’t leave on Nhibernate logging… it kills your app.
Commenting out log4net returned everything to normal, now we just need to log the correct things (ie not every NHibernate interaction!)

Post sharp

It looks like you can hold a reference to the method you are entering and exiting by using the MethodExecutionTag.
You can assign what you want to it as it is just an object and is bound to the eventArgs of the enter and exit events.
Sweet.
This means you could also make every single method a transaction if you wanted to (if you were Juval Lowy/mad man), or mark entry and exit of a specific instance call of a method using a GUID as colleague had mentioned would be nice for logging.
As this is weaved in to the IL its should have not have any more a negative performance impact on calling the method, over over putting the code in to the method to do exactly the same. You do however have a whole load more flexibility to pull out and put in what you want and where (ie certain assemblies, classes or methods).
I am loving PostSharp 🙂

AOP vs IoC/DI???

An explanation to a colleague today that may be easier to understand than the typical ambiguous answer that he had recieved: “oh yeah its when you want to shove something in from the side”

AOP is different to IoC or Dependency injection (which is what Object Builder is) and can be used in conjunction with it.

IoC lets you code to interfaces and create object instances at runtime by calling the IoC Container (or dynamic factory) at runtime with the string key or Interface, to give you a concrete implementation of that interface (or sometime base class).

Spring.net and Windsor/Castle are the most popular open source IoC Containers and they both kind of do AOP as well, but it’s a bit convoluted.

Most people use AOP for “cross cutting concerning”, things like Logging, Security, Exception handling where you want a standard way of handling these things up and down the stack. The problem is that often at each tier, or even layer you get different people doing different things and it also mean you have code bloat like:

Public void MethodX(Type1 param1, int param2)
{
Log.(“enter MethodX);//Logging
Check.UserCanDo(MethodX);//Security
Try
{
Check.Ensure(param1 != null,”param1 can not be null”);//DBC
Check.Ensure(param2 > 10,”param2 must be greater than 10”);//DBC
… //Business logic
}
Catch(ExceptionY ey)//Exception handling
{
GlobalExceptionHandler.DoStandardExceptionHandling(ey);
Throw;
}
}

Where that whole thing can now be refactored to:

[StandardPublicMethodAOPHandler]//Logging, Security, Exception handling
Public void MethodX()
{
Check.Ensure(param1 != null,”param1 can not be null”);//DBC
Check.Ensure(param2 > 10,”param2 must be greater than 10”);//DBC
… //Business logic
}

Even better you can put that attribute on the method/class/assembly and then the normal devs don’t even have to worry about following standard procedure and code is a whole lot easier to read.

HTH. 🙂

Using AOP

I have been dodging AOP for a while now for the main reason that is “Looks to hard”, especially when you have to explain it to PM’s and other dev’s who are still trying to get to grips with basic IoC and ORM concepts, after all projects are not solo efforts.
However I have now found a nice looking framework that may help.
PostSharp is an Attribute driven lightweight AOP framework that modifies the IL as a Post build event in the .Net framework.
This article here has got me very excited about implementing standardised Logging, Security, Exception Handling and maybe even Design by Contract.

Once i get my home development PC back from the dead I will post more about how easy it is (or isnt) and how it affect the project at runtime.
Should be interesting.