MemoryOutputCache.cs 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Runtime.Caching;
  4. namespace iiie.CacheControl.Business.OutputCache
  5. {
  6. public class MemoryOutputCache : IOutputCache
  7. {
  8. private static readonly MemoryCache Cache = MemoryCache.Default;
  9. public void RemoveStartsWith(string key)
  10. {
  11. lock (Cache)
  12. {
  13. Cache.Remove(key);
  14. }
  15. }
  16. public T Get<T>(string key) where T : class
  17. {
  18. var o = Cache.Get(key) as T;
  19. return o;
  20. }
  21. public object Get(string key)
  22. {
  23. return Cache.Get(key);
  24. }
  25. public void Remove(string key)
  26. {
  27. lock (Cache)
  28. {
  29. Cache.Remove(key);
  30. }
  31. }
  32. public bool Contains(string key)
  33. {
  34. return Cache.Contains(key);
  35. }
  36. public void Add(string key, object o, string dependsOnKey = null)
  37. {
  38. var cachePolicy = new CacheItemPolicy();
  39. if (!string.IsNullOrWhiteSpace(dependsOnKey))
  40. {
  41. cachePolicy.ChangeMonitors.Add(
  42. Cache.CreateCacheEntryChangeMonitor(new[] { dependsOnKey })
  43. );
  44. }
  45. lock (Cache)
  46. {
  47. Cache.Add(key, o, cachePolicy);
  48. }
  49. }
  50. public IEnumerable<string> AllKeys
  51. {
  52. get
  53. {
  54. return Cache.Select(x => x.Key);
  55. }
  56. }
  57. }
  58. }