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?
PS/ I'm sticked to .Net 3.5
() => ComputeExpensiveResult()
, or even justComputeExpensiveResult
. Also,GetSomeCachedData()
should probably be a property. – svick May 7 '13 at 16:55