PostSharp – take one

I have known about, or should I say heard about, aspect oriented programming (or AOP) for a while now but never tried it out until recently. I thought I´d share my experiences about it.
So, I decided to use PostSharp. I know, there are a lot of them out there…frameworks I mean, but I got a good feeling for this one.

First thing, download framework from the site and run the installer. Add the PostSharp.Laos.dll and PostSharp.Public.dll to your project.

image

The Attribute

Create an attribute that derives from one of the aspects in the framework. The OnMethodBoundaryAspect that I´m using here will make it possible for me to intercept entering the method but also a sort of try catch finally where I can intercept if the method will throw an exception. This only demonstrates a simple example that writes the method name and values of parameters to the console.

[Serializable]
class TraceAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionEventArgs context)
    {
        Console.Write("Entering method '{0}' with arguments [", context.Method.Name);

        foreach (var item in context.GetReadOnlyArgumentArray())
        {
            Console.Write(" '{0}'", item);
        }

        Console.Write(" ]");
        Console.WriteLine();
    }
}

The example code

Decorate a method with the attribute and hit it!

static void Main(string[] args)
{

    WriteToConsole("From the Main method", "Main");
    Console.ReadKey();
}

 

[Trace]
static void WriteToConsole(string text, string category)
{
    Console.WriteLine("{0}; {1}", category, text);
}

 

 

As you can see I´m calling the method with two parameters and they are written to the console. Compile and run.

image

But wait, what happened here, My method got intercepted and the code I wrote in the attribute got written to the console first.

How was that possible? Well, the framework post compiled my assembly and injected code into the MSIL. A quick look at reflector reveals the injected code as you see here:

image

Summary: I love this sort of programming. My method only includes the core code that it needs. The boilerplate code will be in the aspects and the great thing is that I can reuse the aspects throughout my application.

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: