Aspect Oriented Programming in .Net using PostSharp

I saw this article on D. Patrick Caldwell’s blog a little while back:

http://dpatrickcaldwell.blogspot.com/2009/03/validate-parameters-using-attributes.html

It was this article that got me interested in PostSharp and the possibilities that it can bring. PostSharp, in short, is a lightweight framework which introduces some Aspect-Oriented Programming into .Net.

Some of the common usages I have seen include tracing and the ‘memorizer‘ (again, from D. Patrick Caldwell’s blog) being one of the more interesting. There is also a blog entry over at Richard’s Braindump which highlights how you can use PostSharp to implement the INotifyPropertyChanged interface.

One thing I’d like to point out though, is that the parameter validation technique in D. Patrick Caldwell’s blog entry above should be used with care and you should avoid applying the [CheckParameters] attribute at class/assembly level as it does carry some performance hits. After playing around and experimenting with it for a little while, I have settled on applying the [CheckParameters] attribute only on methods whose parameters require validation.

In my line of work, we have a lot of problems with deadlocks in the DataBase due to the number of different applications using the same Tables in the DataBase and the different way they use these tables (some uses nolock, others don’t). As a result, there are a lot of boilerplate code in the DAL classes which catches SqlExceptions and in case of deadlocks or connection timeouts retry up to x number times. This, of course, is a cross-cutting concern, and by employing PostSharp I am able to deal with them with a simple attribute like the one below instead of hundreds and hundreds lines of code.

[Serializable]
[AttributeUsage(AttributeTargets.Method)]
public class RetryOnSqlDeadLockOrConnectionTimeOutExceptionAttribute : OnMethodInvocationAspect
{
     [NonSerialized]
     private int CurrentAttempt;

     public override void OnInvocation(MethodInvocationEventArgs eventArgs)
     {
          CurrentAttempt++;

          try
          {
               eventArgs.Proceed();
          }
          catch (SqlException sqlException)
          {
               if (sqlException.Number == -2 || sqlException.Number == 1205)
               {
                    // put retry logic here
               }
               else
                    throw;
          }
     }
}

and to use it:

[RetryOnSqlDeadLockOrConnectionTimeOutException]
public void SomeDataBaseBoundOperationWhichNeedsRetryOnDataBaseDeadLock()
{
     ...
}

3 thoughts on “Aspect Oriented Programming in .Net using PostSharp”

  1. Pingback: .Net Tips — use DebuggerStepThrough attribute | theburningmonk.com

  2. Pingback: AOP — FIFO Memoizer with PostSharp | theburningmonk.com

Leave a Comment

Your email address will not be published. Required fields are marked *