diff --git a/AsbCloudInfrastructure/Services/Cache/CacheDb.cs b/AsbCloudInfrastructure/Services/Cache/CacheDb.cs index ddf34de8..73630000 100644 --- a/AsbCloudInfrastructure/Services/Cache/CacheDb.cs +++ b/AsbCloudInfrastructure/Services/Cache/CacheDb.cs @@ -1,4 +1,5 @@ -using Microsoft.EntityFrameworkCore; +using System; +using Microsoft.EntityFrameworkCore; using System.Collections.Concurrent; using System.Collections.Generic; @@ -7,7 +8,8 @@ namespace AsbCloudInfrastructure.Services.Cache public class CacheDb { - private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); + private readonly ConcurrentDictionary)> cache = new ConcurrentDictionary)>(); + private readonly TimeSpan obsolesenceTime = TimeSpan.FromMinutes(15); public CacheTable GetCachedTable(DbContext context) where TEntity : class @@ -15,9 +17,15 @@ namespace AsbCloudInfrastructure.Services.Cache var entityTypeName = typeof(TEntity).FullName; if (!cache.ContainsKey(entityTypeName)) - cache[entityTypeName] = new List(8); + cache[entityTypeName] = (DateTime.Now, new List(8)); + + bool isCachedDataObsolete = DateTime.Now - cache[entityTypeName].Item1 > obsolesenceTime; + + var tableCache = new CacheTable(context, cache[entityTypeName]); + + if (isCachedDataObsolete) + tableCache.Refresh(); - var tableCache = new CacheTable(context, (List)cache[entityTypeName]); return tableCache; } diff --git a/AsbCloudInfrastructure/Services/Cache/CacheTable.cs b/AsbCloudInfrastructure/Services/Cache/CacheTable.cs index 4f85ea43..0def1e23 100644 --- a/AsbCloudInfrastructure/Services/Cache/CacheTable.cs +++ b/AsbCloudInfrastructure/Services/Cache/CacheTable.cs @@ -10,12 +10,14 @@ namespace AsbCloudInfrastructure.Services.Cache public class CacheTable where TEntity : class { private readonly DbContext context; + private (DateTime refreshDate, IEnumerable entities) data; private readonly List cached; - internal CacheTable(DbContext context, List entities) + internal CacheTable(DbContext context, (DateTime refreshDate, IEnumerable entities) data) { this.context = context; - this.cached = entities; + this.data = data; + this.cached = (List)data.entities; } public TEntity this[int index] { get => cached.ElementAt(index); } @@ -25,6 +27,7 @@ namespace AsbCloudInfrastructure.Services.Cache cached.Clear(); var dbEntities = context.Set().ToList(); cached.AddRange(dbEntities); + data.refreshDate = DateTime.Now; return cached.Count; } @@ -33,6 +36,7 @@ namespace AsbCloudInfrastructure.Services.Cache cached.Clear(); var dbEntities = await context.Set().ToListAsync(token).ConfigureAwait(false); cached.AddRange(dbEntities); + data.refreshDate = DateTime.Now; return cached.Count; }