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

40 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
{
2021-10-03 20:08:17 +05:00
private readonly Dictionary<string, (DateTime, IEnumerable)> cache =
new Dictionary<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
if (!cache.ContainsKey(entityTypeName))
2021-10-03 20:08:17 +05:00
cache[entityTypeName] = (DateTime.Now, new List<TEntity>());
bool isCachedDataObsolete = DateTime.Now - cache[entityTypeName].Item1 > obsolesenceTime;
var tableCache = new CacheTable<TEntity>(context, cache[entityTypeName]);
if (isCachedDataObsolete)
tableCache.Refresh();
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
}
}