Caching using aspect oriented programming with PostSharp
I’ve been hoping to add some caching to an application recently. It’s not a slow app, per se, but I figure that some caching is probably better than no caching and I’m expecting the app to grow, so it’d be nice to have the extra scalability available in the future.
My solution makes use of aspect oriented programming through PostSharp in C#. If you’re unfamiliar with AOP, the gist of it is that we’re modifying the behavior of methods before and after they’ve been called. In this case, I check a globally accessible cache before the method is executed to determine if I’ve got a cached result and, if so, return that instead of calling the method. After the method has been called, the result is stored in the cache so that the next time it’s called, we can use the stored value instead of executing the expensive method a second time.