using Microsoft.Extensions.Caching.Distributed; using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Netmash.Extensions.Caching.Services { internal class CacheService : ICacheService { private readonly IDistributedCache _cache; private static readonly ConcurrentDictionary _keys = new ConcurrentDictionary(); const int expirationTimeFromNow = 24; public CacheService(IDistributedCache cache) { _cache = cache; } public async Task GetAsync(string key, CancellationToken token = default(CancellationToken)) where T : class { var result = await _cache.GetAsync(key, token); return result; } public async Task SetApplicationDataAsync(string key, T value, CancellationToken token = default(CancellationToken)) where T : class { _keys.TryAdd(key, string.Empty); await _cache.SetAsync(key, value, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(expirationTimeFromNow) }, token); } public void Reset() { lock (_keys) { var list = _keys.Keys.ToList(); foreach (var s in list) { _cache.Remove(s); } _keys.Clear(); } } } }