Files
Caspian.Elsa.Core/src/modules/Elsa.Caching/Services/MemoryCacheProvider.cs
T

33 lines
1.2 KiB
C#

using Elsa.Caching.Models;
using Microsoft.Extensions.Caching.Memory;
namespace Elsa.Caching.Services;
public class MemoryCacheProvider(IMemoryCache cache, IChangeTokenSignaler signaler) : ICacheProvider
{
public bool IsShared => false;
public Task<CacheResult<T>> GetAsync<T>(string key, CancellationToken cancellationToken = default)
{
var found = cache.TryGetValue(key, out T? value);
return Task.FromResult(new CacheResult<T>(found, value));
}
public Task SetAsync<T>(string key, T? value, CacheEntryOptions options, CancellationToken cancellationToken = default)
{
var memoryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow,
SlidingExpiration = options.SlidingExpiration
};
foreach (var tag in options.Tags) memoryOptions.AddExpirationToken(signaler.GetToken(tag));
cache.Set(key, value, memoryOptions);
return Task.CompletedTask;
}
public Task RemoveAsync(string key, CancellationToken cancellationToken = default)
{
cache.Remove(key);
return Task.CompletedTask;
}
}