I’ve been meaning to write this post for months now to talk about my work with PostSharp and Attribute Based Caching. PostSharp is an AOP tool – I won’t get into too much detail about AOP and PostSharp as I have provided links to them
I used PostSharp to remove the amount of code required for the caching of my calls in a legacy application. Traditionally I would have had to write code such as this:
I was able to change the way this was done with AOP. This makes the code snippet look as follows:
I have effectively removed 2 lines of code from EVERY method call and replaced it with an attribute over the method declaration. In order for this to build, I had to either install PostSharp or run it as an import target manually in my .csproj file. So what does the output of the IL look like when decompiled?
You can see that the IL has had Aspects added to it. The 3rd party dll I used (CacheAspect) then knows what to add to the code and this is then IL woven using PostSharp. This means that the results of the MyMethod call will be added to the Cache with the key of StoredProcedureResults.
This has been majorly useful for me since I can invalidate the Cache on specific method calls
This method works by Invalidating the cache (key “StoredProcedureResults”) when the AddMethod is called. This scenario can be very useful when a list of users are cached and a new user is added to the list. It cuts down the code and is easy to read in my opinion.
I have posted before about how to hook PostSharp up to my CI server. AOP is not everyone’s thing. It has been very useful for me on a small project. It has impacted the build time but I think its worth it for DRY code