Memory Cache helper

using System;
using System.Runtime.Caching;

namespace OneTwoThree.Common.Core.Utilty
{
public interface IMemoryCacheHelper
{
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback, int? expireMinutes = 15) where T : class;
}

public class MemoryCacheHelper: IMemoryCacheHelper
{
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback, int? expireMinutes= 15) where T : class
{
T item = MemoryCache.Default.Get(cacheKey) as T;
if (item == null)
{
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(expireMinutes.Value));
}
return item;
}
}
}

Advertisements

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