| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- using System;
- using Microsoft.Extensions.Options;
- using Microsoft.Extensions.Caching.Memory;
- namespace Abp.Runtime.Caching.Memory
- {
- /// <summary>
- /// Implements <see cref="ICache"/> to work with <see cref="MemoryCache"/>.
- /// </summary>
- public class AbpMemoryCache : CacheBase
- {
- private MemoryCache _memoryCache;
- /// <summary>
- /// Constructor.
- /// </summary>
- /// <param name="name">Unique name of the cache</param>
- public AbpMemoryCache(string name)
- : base(name)
- {
- _memoryCache = new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions()));
- }
- public override object GetOrDefault(string key)
- {
- return _memoryCache.Get(key);
- }
- public override void Set(string key, object value, TimeSpan? slidingExpireTime = null, TimeSpan? absoluteExpireTime = null)
- {
- if (value == null)
- {
- throw new AbpException("Can not insert null values to the cache!");
- }
- if (absoluteExpireTime != null)
- {
- _memoryCache.Set(key, value, DateTimeOffset.Now.Add(absoluteExpireTime.Value));
- }
- else if (slidingExpireTime != null)
- {
- _memoryCache.Set(key, value, slidingExpireTime.Value);
- }
- else if (DefaultAbsoluteExpireTime != null)
- {
- _memoryCache.Set(key, value, DateTimeOffset.Now.Add(DefaultAbsoluteExpireTime.Value));
- }
- else
- {
- _memoryCache.Set(key, value, DefaultSlidingExpireTime);
- }
- }
- public override void Remove(string key)
- {
- _memoryCache.Remove(key);
- }
- public override void Clear()
- {
- _memoryCache.Dispose();
- _memoryCache = new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions()));
- }
- public override void Dispose()
- {
- _memoryCache.Dispose();
- base.Dispose();
- }
- }
- }
|