persistence/DD.Persistence.Repository/RepositoriesCached/RelatedDataCachedRepository.cs
Roman Efremov fd276f5a43
Some checks failed
Unit tests / test (push) Failing after 55s
Доработки
2025-01-17 17:21:54 +05:00

38 lines
1.3 KiB
C#

using DD.Persistence.Repository.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace DD.Persistence.Repository.RepositoriesCached;
public class RelatedDataCachedRepository<TDto, TEntity> : RelatedDataRepository<TDto, TEntity>
where TEntity : class, new()
where TDto : class, new()
{
private static readonly string SystemCacheKey = $"{typeof(TEntity).FullName}CacheKey";
private readonly IMemoryCache memoryCache;
private readonly TimeSpan? AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60);
public RelatedDataCachedRepository(DbContext db, IMemoryCache memoryCache) : base(db)
{
this.memoryCache = memoryCache;
}
public override async Task Add(TDto dataSourceSystemDto, CancellationToken token)
{
await base.Add(dataSourceSystemDto, token);
memoryCache.Remove(SystemCacheKey);
}
public override async Task<IEnumerable<TDto>> Get(CancellationToken token)
{
var systems = await memoryCache.GetOrCreateAsync(SystemCacheKey, async (cacheEntry) =>
{
cacheEntry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;
var dtos = await base.Get(token);
return dtos;
});
return systems!;
}
}