AbpMemoryCache.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using Microsoft.Extensions.Options;
  3. using Microsoft.Extensions.Caching.Memory;
  4. namespace Abp.Runtime.Caching.Memory
  5. {
  6. /// <summary>
  7. /// Implements <see cref="ICache"/> to work with <see cref="MemoryCache"/>.
  8. /// </summary>
  9. public class AbpMemoryCache : CacheBase
  10. {
  11. private MemoryCache _memoryCache;
  12. /// <summary>
  13. /// Constructor.
  14. /// </summary>
  15. /// <param name="name">Unique name of the cache</param>
  16. public AbpMemoryCache(string name)
  17. : base(name)
  18. {
  19. _memoryCache = new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions()));
  20. }
  21. public override object GetOrDefault(string key)
  22. {
  23. return _memoryCache.Get(key);
  24. }
  25. public override void Set(string key, object value, TimeSpan? slidingExpireTime = null, TimeSpan? absoluteExpireTime = null)
  26. {
  27. if (value == null)
  28. {
  29. throw new AbpException("Can not insert null values to the cache!");
  30. }
  31. if (absoluteExpireTime != null)
  32. {
  33. _memoryCache.Set(key, value, DateTimeOffset.Now.Add(absoluteExpireTime.Value));
  34. }
  35. else if (slidingExpireTime != null)
  36. {
  37. _memoryCache.Set(key, value, slidingExpireTime.Value);
  38. }
  39. else if (DefaultAbsoluteExpireTime != null)
  40. {
  41. _memoryCache.Set(key, value, DateTimeOffset.Now.Add(DefaultAbsoluteExpireTime.Value));
  42. }
  43. else
  44. {
  45. _memoryCache.Set(key, value, DefaultSlidingExpireTime);
  46. }
  47. }
  48. public override void Remove(string key)
  49. {
  50. _memoryCache.Remove(key);
  51. }
  52. public override void Clear()
  53. {
  54. _memoryCache.Dispose();
  55. _memoryCache = new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions()));
  56. }
  57. public override void Dispose()
  58. {
  59. _memoryCache.Dispose();
  60. base.Dispose();
  61. }
  62. }
  63. }