Created
August 21, 2017 12:14
-
-
Save HoraceBury/55277993ccde29b38bacf05bbdf17819 to your computer and use it in GitHub Desktop.
Generic caching mechanism which makes sliding expiration easy.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Runtime.Caching; | |
namespace CacheServices | |
{ | |
public class Cache | |
{ | |
protected MemoryCache _cache = new MemoryCache("general"); | |
public static CacheItemPolicy DefaultPolicy { get; set; } | |
public static readonly Dictionary<string, CacheItemPolicy> Terms = new Dictionary<string, CacheItemPolicy>() | |
{ | |
{"Short", new CacheItemPolicy {SlidingExpiration = new TimeSpan(0, 0, 30)}}, | |
{"Medium", new CacheItemPolicy {SlidingExpiration = new TimeSpan(0, 5, 0)}}, | |
{"Long", new CacheItemPolicy {SlidingExpiration = new TimeSpan(1, 0, 0)}}, | |
{"Always", new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.MaxValue}} | |
}; | |
static Cache() | |
{ | |
DefaultPolicy = Terms["Short"]; | |
} | |
public object this[string key] | |
{ | |
get { return Get(key); } | |
set { Add(key, value, DefaultPolicy); } | |
} | |
public void Add(string key, object item, CacheItemPolicy term) | |
{ | |
if (item == null) | |
Remove(key); | |
else | |
{ | |
_cache.Remove(key); | |
_cache.Add(key, item, term); | |
} | |
} | |
public object Get(string key) | |
{ | |
return _cache.Get(key); | |
} | |
public object Remove(string key) | |
{ | |
return _cache.Remove(key); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment