Wednesday, November 15, 2006

Extension Methods to the Rescue

Today I added some caching to a prototype application I'm developing at work. Microsoft Enterprise Library was my implementation library of choice, but I was frustrated by the choice of available overloads for CacheManager.Add(). Rather than add my own overload, spoil the clean interface and recompile the assembly, I ended up writing a single method on a static class that took an instance of the CacheManager, key, value and expiration as parameters, adding in the default values in a call to the CacheManager object. Now this may not be object-oriented, but it's very similar to how extension methods work in C# 3.0 (in my opinion, they exist solely to _fake_ the object-orientedness in calling code). In fact, when you declare a class like this:

public static class CacheManagerExtension
public static readonly TimeSpan DefaultAbsoluteExpiration = TimeSpan.FromMinutes(5);
public static void Add(this CacheManager cacheManager, string key, object value, TimeSpan absoluteExpiration)
cacheManager.Add(key, value, ..., new AbsoluteExpiration(absoluteExpiration), ...);

the new C# 3.0 compiler (figuratively speaking) recognises the "this" keyword in the parameter list, and marks the method, class and assembly with the ExtensionAttribute custom attribute. Now, you can call the Add method like this:

cacheManager.Add(key, value, CacheManagerExtension.DefaultAbsoluteExpiration);

and the compiler (and hopefully Intellisense) - upon realising that no method with that signature exists on the CacheManager class - will translate it into a call on the static class marked with the ExtensionAttribute attribute.

Oh yeah, and my other gripe with Microsoft Enterprise Library is the fact it's caching is not aspect-oriented, but that's the topic of another post...

Post-script: Don't blindly assume that your service delivery team are happy to install EntLib on the production server. :-)

No comments: