Skip to content

Instantly share code, notes, and snippets.

@miguelludert
Last active December 22, 2015 12:49
Show Gist options
  • Save miguelludert/6475225 to your computer and use it in GitHub Desktop.
Save miguelludert/6475225 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Linq;
namespace Caching
{
public class CacheContainer
{
static readonly ObjectCache Cache = MemoryCache.Default;
/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <returns>Cached item as type</returns>
public static T Get<T>(string key) where T : class
{
if(GetAllKeys().Any(a => a == key))
return (T)Cache[key];
else
return null;
}
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="objectToCache">Item to be cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T objectToCache, string key) where T : class
{
Cache.Add(key, objectToCache, DateTime.Now.AddHours(1));
}
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <param name="objectToCache">Item to be cached</param>
/// <param name="key">Name of item</param>
public static void Add(object objectToCache, string key)
{
Cache.Add(key, objectToCache, DateTime.Now.AddHours(1));
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
Cache.Remove(key);
}
public static void ClearAll()
{
foreach (var k in GetAllKeys())
Cache.Remove(k);
}
/// <summary>
/// Check for item in cache
/// </summary>
/// <param name="key">Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
return Cache.Get(key) != null;
}
/// <summary>
/// Gets all cached items as a list by their key.
/// </summary>
/// <returns></returns>
public static IEnumerable<string> GetAllKeys()
{
return Cache.Select(keyValuePair => keyValuePair.Key);
}
public static TResult Load<TResult>(string key, Func<TResult> loadFunction) where TResult : class
{
key = typeof(TResult).FullName + "~" + key;
var result = default(TResult);
if (CacheContainer.Exists(key))
{
result = CacheContainer.Get<TResult>(key);
}
else
{
result = loadFunction();
if(result != null)
CacheContainer.Add(result,key);
}
return result;
}
public static TResult Reload<TResult>(string key, TResult value) where TResult : class
{
key = typeof(TResult).FullName + "~" + key;
if (GetAllKeys().Contains(key))
Cache[key] = value;
else
Add<TResult>(value, key);
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment