Cybercrux

Everything is achievable through technology

Cache Helper MVC

using System;
using System.Web;
using System.Web.Caching;

public class CacheService : ICacheService
{
public CacheService()
{
}

public T GetCache(string cacheId, Func getItemCallback) where T : class
{
T item = HttpContext.Current.Cache.Get(cacheId) as T;
if (item == null)
{
item = getItemCallback();
HttpContext.Current.Cache.Insert(cacheId, item);
//HttpContext.Current.Cache.Insert(cacheId, item, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.Normal, null);
}
return item;
}

public T GetCache(string cacheId) where T : class
{
T item = HttpContext.Current.Cache.Get(cacheId) as T;
return item;
}

public T GetSession(string sessionId, Func getItemCallback) where T : class
{
T item = HttpContext.Current.Session[sessionId] as T;
if (item == null)
{
item = getItemCallback();
HttpContext.Current.Session[sessionId] = item;
}
return item;
}

public void RemoveSession(string sessionId)
{
HttpContext.Current.Session.Remove(sessionId);
}

public void RemoveCache(string cacheId)
{
HttpRuntime.Cache.Remove(cacheId);
}
}

public interface ICacheService
{
T GetCache(string cacheId, Func getItemCallback) where T : class;
T GetSession(string sessionId, Func getItemCallback) where T : class;
T GetCache(string cacheId) where T : class;
void RemoveSession(string sessionId);
void RemoveCache(string cacheId);
}

Leave a comment