DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/Cache/CacheDb.cs
2021-10-18 11:06:42 +05:00

39 lines
1.2 KiB
C#

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