DD.WellWorkover.Cloud/AsbCloudInfrastructure/Repository/CacheBase.cs

62 lines
1.9 KiB
C#
Raw Normal View History

using AsbCloudDb.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
2024-08-19 10:01:07 +05:00
namespace AsbCloudInfrastructure.Repository;
public class CacheBase<TEntity> : QueryContainer<TEntity>
where TEntity : class, AsbCloudDb.Model.IId
{
2024-08-19 10:01:07 +05:00
protected readonly IMemoryCache memoryCache;
protected string CacheTag = typeof(TEntity).Name;
protected TimeSpan CacheObsolescence = TimeSpan.FromMinutes(5);
2024-08-19 10:01:07 +05:00
public CacheBase(IAsbCloudDbContext context, IMemoryCache memoryCache)
: base(context)
{
2024-08-19 10:01:07 +05:00
this.memoryCache = memoryCache;
}
2024-08-19 10:01:07 +05:00
public CacheBase(IAsbCloudDbContext context, IMemoryCache memoryCache, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery)
: base(context, makeQuery)
{
this.memoryCache = memoryCache;
}
2024-08-19 10:01:07 +05:00
protected virtual void DropCache()
=> memoryCache.Remove(CacheTag);
2024-08-19 10:01:07 +05:00
protected virtual IEnumerable<TEntity> GetCache()
{
var cache = memoryCache.GetOrCreate(CacheTag, cacheEntry =>
{
2024-08-19 10:01:07 +05:00
cacheEntry.AbsoluteExpirationRelativeToNow = CacheObsolescence;
cacheEntry.SlidingExpiration = CacheObsolescence;
var entities = this.GetQuery().ToArray();
cacheEntry.Value = entities;
return entities;
});
return cache!;
}
2024-08-19 10:01:07 +05:00
protected virtual async Task<IEnumerable<TEntity>> GetCacheAsync(CancellationToken token)
{
var cache = await memoryCache.GetOrCreateAsync(CacheTag, async (cacheEntry) =>
{
2024-08-19 10:01:07 +05:00
cacheEntry.AbsoluteExpirationRelativeToNow = CacheObsolescence;
cacheEntry.SlidingExpiration = CacheObsolescence;
var entities = await GetQuery().AsNoTracking().ToArrayAsync(token);
cacheEntry.Value = entities;
return entities.AsEnumerable();
});
return cache!;
}
}