Cache Snippet

Here’s a little code snippet that will handle caching of objects using http runtime cache. If object exists in cache it will be returned. If not it will be reloaded using the supplied method, inserted into cache and returned back.

public static class Cacher
{
    public static T Get<T>(Func<T> action, int duration = 24)
    {
        // Gets the hash code of the action instance to use as cache key
        var key = action.GetHashCode().ToString();

        // Return if exists in cache
        if (HttpRuntime.Cache[key] != null)
        {
            return (T)HttpRuntime.Cache[key];
        }

        // Execute the supplied method
        T result = action();

        // If result, insert into cache
        if (result != null)
        {
            HttpRuntime.Cache.Insert(key,
                result,
                null,
                DateTime.UtcNow.AddHours(duration),
                Cache.NoSlidingExpiration);
        }
        // Else remove from cache
        else
        {
            HttpRuntime.Cache.Remove(key);
        }

        // Return result
        return result;
    }
}

Usage:

var items = Cacher.Get(() => MyRepository.GetItems());