Skip to main content
2 of 3
deleted 6 characters in body; edited tags
Jamal
  • 35.2k
  • 13
  • 134
  • 238

ASP.Net caching helper

I'm willing to simplify the use of the ASP.NET cache. I wrote this helper class:

public static class CacheHelper
{
    public static T GetCached<T>(string key, Func<T> initializer, DateTime absoluteExpiration)
    {
        return GetCached(key, initializer, Cache.NoSlidingExpiration, absoluteExpiration);
    }
    public static T GetCached<T>(string key, Func<T> initializer, TimeSpan slidingExpiration)
    {
        return GetCached(key, initializer, slidingExpiration, Cache.NoAbsoluteExpiration);
    }
    public static T GetCached<T>(string key, Func<T> initializer, TimeSpan slidingExpiration, DateTime absoluteExpiration)
    {
        var httpContext = HttpContext.Current;

        if (httpContext != null)
        {
            var obj = httpContext.Cache[key];
            if (obj == null)
            {
                obj = initializer();
                httpContext.Cache.Add(key, obj, null, absoluteExpiration, slidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
            }
            return (T)obj;
        }
        else
        {

            return initializer(); // no available cache
        }
    }
}

The idea is to let the developer write its method as usual, but wrapping it like this:

public MyClass GetSomeCachedData(){
            return CacheHelper.GetCached(
                "GetSomeCachedData, () =>
                {
                    
                        return ComputeExpensiveResult();
                }
                }, TimeSpan.FromMinutes(1), Cache.NoAbsoluteExpiration);
}

Do you see any improvement / issue?

(I'm sticking to .NET 3.5)

Steve B
  • 305
  • 3
  • 10