forked from ddrilling/AsbCloudServer
39 lines
1.2 KiB
C#
39 lines
1.2 KiB
C#
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, object)> cache =
|
|
new ConcurrentDictionary<string, (DateTime, 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 ConcurrentBag<TEntity>());
|
|
|
|
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 _);
|
|
}
|
|
}
|