MemoryCacheProvider.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using Bowin.Common.JSON;
  8. using Microsoft.Extensions.Caching.Memory;
  9. using Microsoft.Extensions.DependencyInjection;
  10. namespace Bowin.Common.Cache
  11. {
  12. public class MemoryCacheProvider : ICacheProvider
  13. {
  14. private IMemoryCache cache { get; set; }
  15. public MemoryCacheProvider()
  16. { }
  17. public MemoryCacheProvider(IMemoryCache _cache)
  18. {
  19. cache = _cache;
  20. }
  21. //private static MemoryCache cache
  22. //{
  23. // get
  24. // {
  25. // return new MemoryCache(new MemoryCacheOptions { });
  26. // }
  27. //}
  28. public void Config(IServiceCollection service)
  29. {
  30. service.AddMemoryCache();
  31. }
  32. public object Add(string key, object entry)
  33. {
  34. var result = Get(key);
  35. if (result != null)
  36. {
  37. cache.Remove(key);
  38. }
  39. using (var cacheEntry = cache.CreateEntry(key))
  40. {
  41. cacheEntry.AbsoluteExpiration = DateTime.Now.AddYears(2);
  42. cacheEntry.Value = entry;
  43. }
  44. result = entry;
  45. return result;
  46. }
  47. public object Add(string key, object entry, DateTime utcExpiry)
  48. {
  49. var result = Get(key);
  50. if (result != null)
  51. {
  52. cache.Remove(key);
  53. }
  54. using (var cacheEntry = cache.CreateEntry(key))
  55. {
  56. cacheEntry.AbsoluteExpiration = utcExpiry;
  57. cacheEntry.Value = entry;
  58. }
  59. result = entry;
  60. return result;
  61. }
  62. public object Get(string key)
  63. {
  64. object result;
  65. if (cache.TryGetValue(key, out result))
  66. {
  67. return result;
  68. }
  69. else
  70. {
  71. return null;
  72. }
  73. }
  74. public void Remove(string key)
  75. {
  76. cache.Remove(key);
  77. }
  78. public void Set(string key, object entry)
  79. {
  80. Add(key, entry);
  81. }
  82. public void Set(string key, object entry, DateTime utcExpiry)
  83. {
  84. Add(key, entry, utcExpiry);
  85. }
  86. }
  87. }