using Microsoft.EntityFrameworkCore; using System; using System.Collections.Concurrent; using System.Collections.Generic; namespace AsbCloudInfrastructure.Services.Cache { public class CacheDb { private readonly ConcurrentDictionary<string, (DateTime, IEnumerable<object>)> cache = new ConcurrentDictionary<string, (DateTime, IEnumerable<object>)>(); private readonly TimeSpan obsolesenceTime = TimeSpan.FromMinutes(15); public CacheTable<TEntity> GetCachedTable<TEntity>(DbContext context) where TEntity : class { var entityTypeName = typeof(TEntity).FullName; if (!cache.ContainsKey(entityTypeName)) cache[entityTypeName] = (DateTime.Now, new List<TEntity>(8)); bool isCachedDataObsolete = DateTime.Now - cache[entityTypeName].Item1 > obsolesenceTime; var tableCache = new CacheTable<TEntity>(context, cache[entityTypeName]); if (isCachedDataObsolete) tableCache.Refresh(); return tableCache; } public void DropAll() => cache.Clear(); public void Drop<TEntity>() => cache.Remove(typeof(TEntity).FullName, out _); } }