Files
annotations/Azaion.Common/Services/Cache.cs
T
Oleksandr Bezdieniezhnykh fd95d2ba2c add MediaHash. Step1
2025-11-17 07:46:05 +02:00

39 lines
1.2 KiB
C#

using LazyCache;
namespace Azaion.Common.Services;
public interface ICache
{
T GetFromCache<T>(string key, Func<T> fetchFunc, TimeSpan? expiration = null);
Task<T> GetFromCacheAsync<T>(string key, Func<Task<T>> fetchFunc, TimeSpan? expiration = null);
void Invalidate(string key);
}
public class MemoryCache : ICache
{
private readonly IAppCache _cache = new CachingService();
public T GetFromCache<T>(string key, Func<T> fetchFunc, TimeSpan? expiration = null)
{
expiration ??= TimeSpan.FromHours(4);
return _cache.GetOrAdd(key, entry =>
{
var result = fetchFunc();
entry.AbsoluteExpirationRelativeToNow = expiration;
return result;
});
}
public async Task<T> GetFromCacheAsync<T>(string key, Func<Task<T>> fetchFunc, TimeSpan? expiration = null)
{
expiration ??= TimeSpan.FromHours(4);
return await _cache.GetOrAddAsync(key, async entry =>
{
var result = await fetchFunc();
entry.AbsoluteExpirationRelativeToNow = expiration;
return result;
});
}
public void Invalidate(string key) => _cache.Remove(key);
}