DD.WellWorkover.Cloud/AsbCloudInfrastructure/Services/Cache/CacheDb.cs

39 lines
1.2 KiB
C#
Raw Normal View History

2021-07-21 15:29:19 +05:00
using Microsoft.EntityFrameworkCore;
using System;
2021-10-03 20:08:17 +05:00
using System.Collections;
using System.Collections.Concurrent;
2021-04-23 10:21:25 +05:00
using System.Collections.Generic;
2021-04-07 18:01:56 +05:00
namespace AsbCloudInfrastructure.Services.Cache
{
public class CacheDb
2021-04-23 10:21:25 +05:00
{
private readonly ConcurrentDictionary<string, (DateTime, IEnumerable)> cache =
new ConcurrentDictionary<string, (DateTime, IEnumerable)>();
private readonly TimeSpan obsolesenceTime = TimeSpan.FromMinutes(15);
2021-04-07 18:01:56 +05:00
public CacheTable<TEntity> GetCachedTable<TEntity>(DbContext context)
2021-04-07 18:01:56 +05:00
where TEntity : class
{
var entityTypeName = typeof(TEntity).FullName;
2021-04-07 18:01:56 +05:00
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)
2021-11-10 17:05:57 +05:00
tableCache.Refresh(true);
2021-04-07 18:01:56 +05:00
return tableCache;
}
2021-04-23 10:21:25 +05:00
public void DropAll() => cache.Clear();
public void Drop<TEntity>() => cache.Remove(typeof(TEntity).FullName, out _);
2021-04-07 18:01:56 +05:00
}
}