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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s