DD.WellWorkover.Cloud/AsbCloudInfrastructure/MemoryCacheExtentions.cs

45 lines
1.6 KiB
C#
Raw Normal View History

2022-11-18 15:07:27 +05:00
using AsbCloudDb.Model;
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
{
public static class MemoryCacheExtentions
{
private static readonly TimeSpan CacheOlescence = TimeSpan.FromMinutes(5);
public static Task<IEnumerable<T>> GetOrCreateBasicAsync<T>(this IMemoryCache memoryCache, IAsbCloudDbContext dbContext, CancellationToken token)
where T : class
{
var cacheTag = typeof(T).FullName;
var cache = memoryCache.GetOrCreateAsync(cacheTag, async (cacheEntry) => {
cacheEntry.AbsoluteExpirationRelativeToNow = CacheOlescence;
cacheEntry.SlidingExpiration = CacheOlescence;
var entities = await dbContext.Set<T>().ToArrayAsync(token);
return entities.AsEnumerable();
});
return cache;
}
public static IEnumerable<T> GetOrCreateBasic<T>(this IMemoryCache memoryCache, IAsbCloudDbContext dbContext)
where T : class
{
var cacheTag = typeof(T).FullName;
var cache = memoryCache.GetOrCreate(cacheTag, cacheEntry => {
cacheEntry.AbsoluteExpirationRelativeToNow = CacheOlescence;
cacheEntry.SlidingExpiration = CacheOlescence;
var entities = dbContext.Set<T>().ToArray();
return entities.AsEnumerable();
});
return cache;
}
}
}