I have written a generic Cache Helper which adds new methods to any object of type T which will add the object to either the global (application) or user (session) cache. It uses the HttpContext.Current.Cache underneath.
Example on how to use the class:
public MyType GetMyObject()
{
MyType myObject;
if(CacheHelper.TryGetFromCache(“key”, out myObject))
{
return myObject;
}
//fetch/create a new object, then cache it and return it
myObject = CreateNewMyObject();
myObject.AddToApplicationCache(“key”);
return myObject;
}
Here’s the code for the Cache Helper:
public static class CacheHelper
{
public static void AddToSessionCache<T>(this T item, string key) where T : class
{
HttpContext.Current.Session.Add(key, item);
}
public static void AddToApplicationCache<T>(this T item, string key) where T : class
{
AddToApplicationCache(item, key, Cache.NoSlidingExpiration, null);
}
public static void AddToApplicationCache<T>(this T item, string key, TimeSpan slidingExpiration) where T : class
{
AddToApplicationCache(item, key, slidingExpiration, null);
}
public static void AddToApplicationCache<T>(this T item, string key, TimeSpan slidingExpiration, CacheDependency dependency) where T : class
{
HttpContext.Current.Cache.Add(key, item, null, Cache.NoAbsoluteExpiration, slidingExpiration, CacheItemPriority.Normal, null);
}
public static bool TryGetFromCache<T>(string key, out T item) where T : class
{
if (HttpContext.Current.Session[key] != null)
{
item = HttpContext.Current.Session[key] as T;
return true;
}
if (HttpContext.Current.Cache[key] != null)
{
item = HttpContext.Current.Cache[key] as T;
return true;
}
item = null;
return false;
}
}
Please use as you will, and at your own risk.
No comments:
Post a Comment