using AsbCloudDb.Model;
using AsbCloudInfrastructure.EfCache;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace AsbCloudInfrastructure.Services
{
#nullable enable
///
/// CRUD сервис с кешем в оперативке
///
///
///
public class CrudCacheServiceBase : CrudServiceBase
where TDto : AsbCloudApp.Data.IId
where TEntity : class, AsbCloudDb.Model.IId
{
protected string CacheTag = typeof(TDto).Name;
protected TimeSpan CacheOlescence = TimeSpan.FromMinutes(5);
protected int KeySelector(TEntity entity) => entity.Id;
public CrudCacheServiceBase(IAsbCloudDbContext dbContext)
: base(dbContext) { }
public CrudCacheServiceBase(IAsbCloudDbContext dbContext, ISet includes)
: base(dbContext, includes) { }
public CrudCacheServiceBase(IAsbCloudDbContext dbContext, Func, IQueryable> makeQuery)
: base(dbContext, makeQuery) { }
///
public override async Task InsertAsync(TDto newItem, CancellationToken token)
{
var result = await base.InsertAsync(newItem, token);
if (result > 0)
DropCache();
return result;
}
///
public override async Task InsertRangeAsync(IEnumerable dtos, CancellationToken token)
{
var result = await base.InsertRangeAsync(dtos, token);
if (result > 0)
DropCache();
return result;
}
///
public override async Task> GetAllAsync(CancellationToken token)
{
var result = await GetQuery()
.FromCacheDictionaryAsync(CacheTag, CacheOlescence, KeySelector, Convert, token);
return result.Values;
}
///
/// Синхронно получить запись по ИД
///
///
///
public override TDto? Get(int id)
{
var result = GetQuery()
.FromCacheDictionary(CacheTag, CacheOlescence, KeySelector, Convert);
return result.GetValueOrDefault(id);
}
///
public override async Task GetAsync(int id, CancellationToken token)
{
var result = await GetQuery()
.FromCacheDictionaryAsync(CacheTag, CacheOlescence, KeySelector, Convert, token);
return result.GetValueOrDefault(id);
}
///
public override async Task UpdateAsync(TDto dto, CancellationToken token)
{
var result = await base.UpdateAsync(dto, token);
if (result > 0)
DropCache();
return result;
}
///
public override async Task UpdateRangeAsync(IEnumerable dtos, CancellationToken token)
{
var result = await base.UpdateRangeAsync(dtos, token);
if (result > 0)
DropCache();
return result;
}
///
public override async Task DeleteAsync(int id, CancellationToken token)
{
var result = await base.DeleteAsync(id, token);
if (result > 0)
DropCache();
return result;
}
protected virtual Task> GetCacheAsync(CancellationToken token)
=> GetQuery()
.FromCacheDictionaryAsync(CacheTag, CacheOlescence, KeySelector, Convert, token);
protected virtual Dictionary GetCache()
=> GetQuery()
.FromCacheDictionary(CacheTag, CacheOlescence, KeySelector, Convert);
protected virtual void DropCache()
=> dbSet.DropCacheDictionary(CacheTag);
}
#nullable disable
}