Aspect Oriented Programming in .Net using PostSharp

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.

Try the Catalyst beta

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()
{
     ...
}

Whenever you’re ready, here are 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

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 *