Quick introduction to PostSharp

June 30, 2009 Waldemar Mękal

PostSharp is a free library for aspect programming in .NET. It post-processes the compiled assembly during the build process. The current version (at time of writing this post) is 1.5 RC1, which has a couple of improvements when compared to version 1.0, such as the following:

  • aspect inheritance,
  • support for Mono, Silverlight and Compact Framework,
  • performance optimizations.

In this post I will introduce PostSharp in short, based on my initial experiments.

Getting started

PostSharp uses attributes for defining aspects. All you have to do is derive from one of predefined aspects and implement desired behavior. Then, just mark the method or whole class with your attribute and you have your aspect working. It is important that you have to mark your aspect as serializable.

Below, there is a simple example (and probably most popular) – logging.

[Serializable]
public class LogAttribute : OnMethodBoundaryAspect
{
  public override void OnEntry(MethodExecutionEventArgs eventArgs)
  {
    Trace.TraceInformation("Entering {0} method...",
      eventArgs.Method.Name);
  }

  public override void OnExit(MethodExecutionEventArgs eventArgs)
  {
    Trace.TraceInformation("Exiting {0} method...",
      eventArgs.Method.Name);
  }

  public override void OnSuccess(MethodExecutionEventArgs eventArgs)
  {
    Trace.TraceInformation("Success in {0} method...",
      eventArgs.Method.Name);
  }

  public override void OnException(MethodExecutionEventArgs eventArgs)
  {
    Trace.TraceInformation("Exception in {0} method...",
      eventArgs.Method.Name);
  }
}

When you apply this on some methods…

public class Test
{
  [Log]
  public void DoNothing()
  {
  }

  [Log]
  public void ThrowException()
  {
    throw new Exception();
  }
}

and invoke these methods…

public static void Main()
{
  Trace.Listeners.Clear();
  Trace.Listeners.Add(new ConsoleTraceListener());

  Test test = new Test();

  test.DoNothing();
  try { test.ThrowException(); }
  catch { }

  Console.ReadLine();
}

you should see something like this.

PostSharpTesting.vshost.exe Information: 0 :
Entering DoNothing method...
PostSharpTesting.vshost.exe Information: 0 :
Success in DoNothing method...
PostSharpTesting.vshost.exe Information: 0 :
Exiting DoNothing method...
PostSharpTesting.vshost.exe Information: 0 :
Entering ThrowException method...
PostSharpTesting.vshost.exe Information: 0 :
Exception in ThrowException method...
PostSharpTesting.vshost.exe Information: 0 :
Exiting ThrowException method...

In the same way you can cope with any repetitive code (common usage is transaction or exception handling).

Summary

Aspect programming can give you a lot of benefits and help in avoiding repetetiveness. PostSharp makes it really easy to use. I think it is worth a try.

Last posts