forked from ddrilling/AsbCloudServer
70 lines
2.4 KiB
C#
70 lines
2.4 KiB
C#
|
using AsbCloudApp.Data;
|
|||
|
using AsbCloudApp.Services;
|
|||
|
using AsbCloudDb.Model;
|
|||
|
using Mapster;
|
|||
|
using Microsoft.EntityFrameworkCore;
|
|||
|
using Microsoft.Extensions.Caching.Memory;
|
|||
|
using System;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Linq;
|
|||
|
using System.Threading;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace AsbCloudInfrastructure.Repository
|
|||
|
{
|
|||
|
public class CacheBase<TDto, TEntity> : QueryContainer<TEntity>
|
|||
|
where TDto : AsbCloudApp.Data.IId
|
|||
|
where TEntity : class, AsbCloudDb.Model.IId
|
|||
|
{
|
|||
|
protected readonly IMemoryCache memoryCache;
|
|||
|
protected string CacheTag = typeof(TDto).Name;
|
|||
|
protected TimeSpan CacheOlescence = TimeSpan.FromMinutes(5);
|
|||
|
|
|||
|
public CacheBase(IAsbCloudDbContext context, IMemoryCache memoryCache)
|
|||
|
: base(context)
|
|||
|
{
|
|||
|
this.memoryCache = memoryCache;
|
|||
|
}
|
|||
|
|
|||
|
public CacheBase(IAsbCloudDbContext context, IMemoryCache memoryCache, Func<DbSet<TEntity>, IQueryable<TEntity>> makeQuery)
|
|||
|
: base(context, makeQuery)
|
|||
|
{
|
|||
|
this.memoryCache = memoryCache;
|
|||
|
}
|
|||
|
|
|||
|
protected virtual void DropCache()
|
|||
|
=> memoryCache.Remove(CacheTag);
|
|||
|
|
|||
|
protected virtual IEnumerable<TDto> GetCache()
|
|||
|
{
|
|||
|
var cache = memoryCache.GetOrCreate(CacheTag, cacheEntry =>
|
|||
|
{
|
|||
|
cacheEntry.AbsoluteExpirationRelativeToNow = CacheOlescence;
|
|||
|
cacheEntry.SlidingExpiration = CacheOlescence;
|
|||
|
|
|||
|
var entities = this.GetQuery().ToArray();
|
|||
|
var dtos = entities.Select(Convert);
|
|||
|
return dtos.ToArray();
|
|||
|
});
|
|||
|
return cache;
|
|||
|
}
|
|||
|
|
|||
|
protected virtual Task<IEnumerable<TDto>> GetCacheAsync(CancellationToken token)
|
|||
|
{
|
|||
|
var cache = memoryCache.GetOrCreateAsync(CacheTag, async (cacheEntry) =>
|
|||
|
{
|
|||
|
cacheEntry.AbsoluteExpirationRelativeToNow = CacheOlescence;
|
|||
|
cacheEntry.SlidingExpiration = CacheOlescence;
|
|||
|
|
|||
|
var entities = await this.GetQuery().ToArrayAsync(token);
|
|||
|
var dtos = entities.Select(Convert);
|
|||
|
return dtos.ToArray().AsEnumerable();
|
|||
|
});
|
|||
|
return cache;
|
|||
|
}
|
|||
|
|
|||
|
protected virtual TDto Convert(TEntity src) => src.Adapt<TDto>();
|
|||
|
|
|||
|
protected virtual TEntity Convert(TDto src) => src.Adapt<TEntity>();
|
|||
|
}
|
|||
|
}
|