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()
{
     ...
}
Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter


Hi, I’m Yan. I’m an AWS Serverless Hero and the author of Production-Ready Serverless.

I specialise in rapidly transitioning teams to serverless and building production-ready services on AWS.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, callbacks, nested workflows, design patterns and best practices.

Get Your Copy