Skip to content

Instantly share code, notes, and snippets.

@callumbwhyte
Created January 19, 2019 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callumbwhyte/5d8108b0a2d707aa6e7dc136888a8a99 to your computer and use it in GitHub Desktop.
Save callumbwhyte/5d8108b0a2d707aa6e7dc136888a8a99 to your computer and use it in GitHub Desktop.
using System;
using System.Configuration;
using System.Linq;
using System.Runtime.Caching;
namespace CBW.Cache
{
public class MemoryCacheHelper
{
public object GetValue(string key)
{
MemoryCache memoryCache = MemoryCache.Default;
return memoryCache.Get(key);
}
public bool Add(string key, object value, DateTimeOffset absExpiration)
{
MemoryCache memoryCache = MemoryCache.Default;
return memoryCache.Add(key, value, absExpiration);
}
public static void Delete(string key)
{
MemoryCache memoryCache = MemoryCache.Default;
if (memoryCache.Any(kv => kv.Key.StartsWith(key)))
{
var entries = memoryCache.Where(kv => kv.Key.StartsWith(key)).ToList();
foreach (var entry in entries)
{
memoryCache.Remove(entry.Key);
}
}
}
public static T GetOrAddValue<T>(string cacheKey, Func<T> getValueFunction, string cacheDurationConfigKey)
where T : class
{
var cacheDuration = GetCacheDuration(cacheDurationConfigKey);
if (cacheDuration > 0)
{
return GetOrAddValue(cacheKey, getValueFunction, item => DateTime.Now.AddSeconds(cacheDuration));
}
return getValueFunction();
}
public static T GetOrAddValue<T>(string cacheKey, Func<T> getValueFunction, Func<T, DateTime> cacheDurationFunction)
where T : class
{
var cache = new MemoryCacheHelper();
var itemToBeCached = cache.GetValue(cacheKey) as T;
if (itemToBeCached != null)
{
return itemToBeCached;
}
itemToBeCached = getValueFunction();
if (itemToBeCached == null)
{
return null;
}
var cacheDuration = cacheDurationFunction(itemToBeCached);
cache.Add(cacheKey, itemToBeCached, cacheDuration);
return itemToBeCached;
}
private static int GetCacheDuration(string cacheDurationConfigKey)
{
var cacheDurationText = ConfigurationManager.AppSettings[cacheDurationConfigKey];
int cacheDuration;
if (int.TryParse(cacheDurationText, out cacheDuration))
{
return cacheDuration;
}
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment