38 lines
1.3 KiB
C#
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!;
|
|
}
|
|
}
|