Caching objects with HttpRuntime

Caching objects with HttpRuntime

I won’t go into the arguments for using a caching mechanism or not. This post is simply an example for an easy way to cache data.

So if you want to store some object in the cache, you can do so very easy.

var localizedString = Caching.EnsureObject(resourceName,
                                           () => GetOperation(parameter));

As you can see, it really doesn’t matter what type of object the cache will store.

class Caching
{
   private static readonly TimeSpan Duration = new TimeSpan(1, 0, 0);

   /// <summary>
   /// return cached value, or add and return from cache
   /// </summary>
   /// <typeparam name="T"></typeparam>
   /// <param name="cacheKey"></param>
   /// <param name="getObject"></param>
   /// <returns></returns>
   internal static T EnsureObject<T>(string cacheKey, Func<T> getObject)
   {
      var value = HttpRuntime.Cache[cacheKey];
      if (value != null)
      {
         return (T) value;
      }

      value = getObject.Invoke();

      if (value != null)
      {
         var expiration = DateTime.UtcNow.Add(Duration);
         HttpRuntime.Cache.Insert(cacheKey, value, null, expiration, Cache.NoSlidingExpiration);
      }
      return (T) value;
   }

Adjust the duration, or pass it as parameter. Additionally you could pass another delegate for Exception-Handling. This example is meant as a reminder to think about caching again…

Leave a Reply