One Line System.Web Caching Template for .Net

Whenever I have something that rarely changes, but takes a little while to calculate I like to cache it, typically, in ASP.Net’s Web Cache. One example might be a bit of JavaScript I want to return minimised and I can’t use System.Web.Optimization for some reason. So, I was finding myself repeating the same algorithm over and over;

1) Is the item cached already? If yes, return it immediately.

2) Build the item.

3) Cache for next time

4) return the item

It’s not many lines of code, but it’s nevertheless prone to cut and paste error and requires a new unit test each time, and then I came up with this neat little shortcut;

    public class Caching
    {
        static Cache _cache = HttpRuntime.Cache;

        public static T CacheThis<T>(string key, Func<T> resolverFunc)
        {
            // Use our own cache if ASP.Net cache is not available
            Cache cache = _cache;
            if (HttpContext.Current != null)
                cache = HttpContext.Current.Cache;

            // Look for a cached version of key
            var output = (T)cache.Get(key);
            if (output != null)
                // Smashing, we can return this from the cache
                return output;
            else
            {
                // Resolve, cache, return
                output = resolverFunc();
                cache.Insert(key, output, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
                return output;
            }
        }
    }

So basically I templatised the algorithm. Now whenever I want to cache anything I can wrap my code in this neat little one-liner;

            var scriptName = "minifiedMainScript.js";
            return Caching.CacheThis(scriptName, () =>
            {
                // get resource without a cache in the normal way
                var Text = MyLoaderClass.Load(scriptName);
                return Text;
            });

Or literally, this could be written on a single line, but you can put as much logic in that code block as you want. It won’t run unless it needs to. Easy huh?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s