Skip to content

Instantly share code, notes, and snippets.

@kevinblake
Created December 7, 2012 10:03
Show Gist options
  • Save kevinblake/4232254 to your computer and use it in GitHub Desktop.
Save kevinblake/4232254 to your computer and use it in GitHub Desktop.
In Memory Cache wrapper class
using System;
using System.Web.Caching;
namespace Puzzlebox.Caching
{
interface ICacheService
{
T Get<T>(string cacheId, Func<T> getItemCallback) where T : class;
T Get<T>(string cacheId, CacheDependency cacheDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, Func<T> getItemCallback) where T : class;
}
}
using System;
using System.Web;
using System.Web.Caching;
namespace Puzzlebox.Caching
{
public class InMemoryCache : ICacheService
{
public T Get<T>(string cacheId, Func<T> getItemCallback) where T : class
{
return Get(cacheId, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1), getItemCallback);
}
public T Get<T>(string cacheId, CacheDependency cacheDependency, DateTime absoluteExpiration, TimeSpan slidingExpiration, Func<T> getItemCallback) where T : class
{
var item = HttpRuntime.Cache.Get(cacheId) as T;
if (item == null)
{
item = getItemCallback();
HttpContext.Current.Cache.Insert(cacheId, item, cacheDependency, absoluteExpiration, slidingExpiration);
}
return item;
}
}
}
var cachedTime = new InMemoryCache().Get("CachedDateTimeKey", null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5), () =>
{
return DateTime.UtcNow;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment