2024-07-04 11:02:45 +05:00
|
|
|
using AsbCloudDb.Model;
|
2022-12-01 15:56:11 +05:00
|
|
|
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
|
2022-12-01 15:56:11 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
protected readonly IMemoryCache memoryCache;
|
|
|
|
protected string CacheTag = typeof(TEntity).Name;
|
|
|
|
protected TimeSpan CacheObsolescence = TimeSpan.FromMinutes(5);
|
2023-04-18 16:22:53 +05:00
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
public CacheBase(IAsbCloudDbContext context, IMemoryCache memoryCache)
|
|
|
|
: base(context)
|
2022-12-01 15:56:11 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
this.memoryCache = memoryCache;
|
|
|
|
}
|
2022-12-01 15:56:11 +05:00
|
|
|
|
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;
|
|
|
|
}
|
2022-12-01 15:56:11 +05:00
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
protected virtual void DropCache()
|
|
|
|
=> memoryCache.Remove(CacheTag);
|
2022-12-01 15:56:11 +05:00
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
protected virtual IEnumerable<TEntity> GetCache()
|
|
|
|
{
|
|
|
|
var cache = memoryCache.GetOrCreate(CacheTag, cacheEntry =>
|
2022-12-01 15:56:11 +05:00
|
|
|
{
|
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!;
|
|
|
|
}
|
2022-12-01 15:56:11 +05:00
|
|
|
|
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) =>
|
2022-12-01 15:56:11 +05:00
|
|
|
{
|
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!;
|
2022-12-01 15:56:11 +05:00
|
|
|
}
|
|
|
|
}
|