PostSharp - AOP for .NET

by Marcus King 10. January 2011 12:55

Aspect Oriented Programming (AOP) is one of those things I heard mumblings about for sometime and viewed it as some esoteric fringe CS concept that solved a very limited problem set and couldn't help me in my applications.  Then when I started reading more about it my preconceptions were strengthened.  Much of the documentation I saw was extremely confusing and didn't describe the real value of AOP.  Then I saw PostSharp and while it's still the same in theory, the very direct documentation showed me practical examples of how AOP helps us to take our code a step further than OOP and allows us to create more modularized and reusable code.  My reaction was, what have I been missing all this time.  How many hours have I wasted writing the same code I've written hundreds of times before not only in different applications but how many times have I repeated the exact same code in the same application.

Luckily in most cases there are good native features built into the language or third party frameworks that are available to reduce the tedious chore of writing basic code yet again.  However, there are a lot of times when OOP doesn’t provide us with a good way to solve a recurring problem.  I’m guessing since you’ve made it this far in you see that this is the point where AOP steps in and fills the gap left by OOP.  I recently did a video tutorial on improving exception handing  using AOP via PostSharp.  Traditionally in applications we need to catch when certain exceptions are thrown and do something with the exception by either logging it, calling another workflow, wrapping the exception inside of another one, or simply swallowing the exception, or some combination of all.  Let’s say for example we have a class we use to call a remote web service to retrieve data for our application.


  1. public class StockService   
  2. {   
  3.     public StockDetails GetStockDetails(string symbol)   
  4.     {   
  5.         try  
  6.         {   
  7.             //.... call to service    
  8.         }   
  9.         catch (SoapException ex) { throw new StockServiceException("Error Getting Details", ex); }   
  10.     }   
  11.     public decimal GetHistoricalPrice(string symbol)   
  12.     {   
  13.         try  
  14.         {   
  15.             //.... call to service    
  16.         }   
  17.         catch (SoapException ex) { throw new StockServiceException("Error Getting Historical Price", ex); }   
  18.     }   
  19.     public void AddToPortfolio(string symbol, int shares)   
  20.     {   
  21.         try  
  22.         {   
  23.             //.... call to service    
  24.         }   
  25.         catch (SoapException ex) { throw new StockServiceException("Error Adding to portfolio", ex); }   
  26.     }   
  27. }  

Look how often we are repeating the same basic pattern.  We’re making our service call and wrapping any Soap Exception that is thrown in a custom StockServiceException.  Using PostSharp we are able to modularize our code and make the business logic of the StockService class look so much cleaner.



  1. public class StockService   
  2. {   
  3.     [HandleException(SoapException, StockServiceException, "Error Getting Details")]   
  4.     public StockDetails GetStockDetails(string symbol)   
  5.     {           
  6.         //.... call to service      
  7.     }   
  8.     [HandleException(SoapException, StockServiceException, "Error Getting Historical Price")]   
  9.     public decimal GetHistoricalPrice(string symbol)   
  10.     {           
  11.         //.... call to service     
  12.     }   
  13.     [HandleException(SoapException, StockServiceException, "Error Adding To Portfolio")]   
  14.     public void AddToPortfolio(string symbol, int shares)   
  15.     {           
  16.         //.... call to service       
  17.     }   
  18. }  

All we need to do is create an attribute that derives from OnMethodBoundaryAspect that accepts three parameters in the constructor;  the type of exception to handle, the type of exception to wrap the caught exception in, and a message to give to the wrapped exception.



  1. [Serializable]   
  2. public class HandleExceptionAttribute : OnExceptionAspect   
  3. {   
  4.     private Type _expectedException;    
  5.     private Type _wrapInException;    
  6.     private string _message;   
  8.     // Constructor that takes in variable parameters when the attribute is applied       
  9.     public HandleExceptionAttribute(Type expectedExeptionType, Type wrapInExceptionType, string message)   
  10.     {   
  11.         _expectedException = expectedExceptionType;   
  12.         _wrapInException = wrapInExceptionType; _message = message;   
  13.     }   
  15.     // This method checks to see if the exception that was thrown from the method the       
  16.     // attribute was applied on matches the expected exception type we passed into the        
  17.     // constructor of the attribute      
  18.     public override Type GetExceptionType(MethodBase targetMethod)   
  19.     {   
  20.         return _expectedException;   
  21.     }   
  23.     // This method is called when we have guaranteed the exception type thrown matches the       
  24.     // expected exception type passed in the constructor.  It wraps the thrown exception        
  25.     // into a new exception and adds the custom message that was passed into the constructor       
  26.     public override void OnException(MethodExecutionArgs args)   
  27.     {   
  28.         args.FlowBehavior = FlowBehavior.Continue;    
  29.         Exception newException = (Exception)Activator.CreateInstance(_wrapInException, new object[] { _message, _expectedException });    
  30.         throw newException;   
  31.     }   
  32. }  

Another common problem set I solve with PostSharp is caching expensive method calls. I find myself repeating the same basic pattern in projects when I need to implement caching. I’m sure you’re familiar with it.



  1. public Account GetAccount(int accountId)   
  2. {   
  3.     string cacheKey = string.Format("GetAccount_{0}", accountId);   
  4.     Account account = Cache.Get(cacheKey);   
  5.     if (account == null)   
  6.     {   
  7.         account = accountRepository.GetAccount(accountId);   
  8.         Cache.Add(cacheKey, account);   
  9.     }   
  10.     return account;   
  11. }  

We build our cache key and check to see if the item is present if the cache. If it is we return the value pulled from the cache, otherwise we do the necessary work to retrieve/build the item to return and save it in the cache with the cache key we built so that the next time this method is called we can successfully pull the item from the cache. I’ve repeated this pattern over and over again, typically in a business layer when I need to retrieve data from an expensive resource like a database or a web service call or when I do complex logic to construct the object that I need to return. Luckily PostSharp provides a way to centralize all of the caching logic for me so I can concentrate on the business logic. The same method now looks like this



  1. [Cache]   
  2. public Account GetAccount(int accountId)    
  3. {    
  4.     return accountRepository.GetAccount(accountId);    
  5. }  

Once again I simply adorn the method with an attribute and it handles a lot of the repitive code. Here is what the Cache Attribute/Aspect code looks like.



  1. public class CacheAttribute : OnMethodBoundaryAspect    
  2. {    
  3.     public override void OnEntry(MethodExecutionArgs args)    
  4.     {    
  5.         string key = args.Method.Name + "_" + Cache.GenerateKey(args.Arguments);    
  6.         object value = Cache.Get(key);    
  8.         if (value == null)    
  9.         {    
  10.             args.MethodExecutionTag = key;    
  11.         }    
  12.         else    
  13.         {    
  14.             args.ReturnValue = value;    
  15.             args.FlowBehavior = FlowBehavior.Return;    
  16.         }    
  17.     }   
  19.     public override void OnSuccess(MethodExecutionArgs args)    
  20.     {   
  21.         string key = args.MethodExecutionTag.ToString();    
  22.         Cache.Add(key, args.ReturnValue);    
  23.     }   
  24. }  

In the OnEntry method I’m building the cache key and checking to see if the item exists in the cache and if so I’m not letting the target method complete and I’m returning the value pulled from cache. If no item was found in the cache, the execution of the target method proceeds and when the target method successfully executes the OnSuccess override is fired and the item is stored in the cache.


There are a lot more interesting things to do with the two areas of caching and exception handling so I would encourage you to check out my screen casts to learn more.

Tags: , , , ,


Add comment

(Will show your Gravatar icon)

  Country flag

  • Comment
  • Preview


Powered by BlogEngine.NET - Eco Theme by n3o Web Designers