82 lines
3.4 KiB
C#

using Microsoft.Extensions.Caching.Distributed;
namespace EnvelopeGenerator.Application.Extensions
{
public static class CacheExtensions
{
public static Task SetLongAsync(this IDistributedCache cache, string key, long value, DistributedCacheEntryOptions? options = null)
=> options is null
? cache.SetAsync(key, BitConverter.GetBytes(value))
: cache.SetAsync(key, BitConverter.GetBytes(value), options: options);
public static async Task<long?> GetLongAsync(this IDistributedCache cache, string key)
{
var value = await cache.GetAsync(key);
return value is null ? null : BitConverter.ToInt64(value, 0);
}
public static Task SetDateTimeAsync(this IDistributedCache cache, string key, DateTime value, DistributedCacheEntryOptions? options = null)
=> cache.SetLongAsync(key: key, value: value.Ticks, options: options);
public static async Task<DateTime?> GetDateTimeAsync(this IDistributedCache cache, string key)
{
var value = await cache.GetAsync(key);
return value is null ? null : new(BitConverter.ToInt64(value, 0));
}
public static Task SetTimeSpanAsync(this IDistributedCache cache, string key, TimeSpan value, DistributedCacheEntryOptions? options = null)
=> cache.SetLongAsync(key: key, value: value.Ticks, options: options);
public static async Task<TimeSpan?> GetTimeSpanAsync(this IDistributedCache cache, string key)
{
var value = await cache.GetAsync(key);
return value is null ? null : new(BitConverter.ToInt64(value, 0));
}
public static string GetOrSet(this IDistributedCache cache, string key, Func<string> factory, DistributedCacheEntryOptions? options = null, bool cacheInBackground = false, CancellationToken token = default)
{
var value = cache.GetString(key);
if (value is null)
{
// create new and save
value = factory();
void Cache()
{
if (options is null)
cache.SetString(key: key, value: value);
else
cache.SetString(key: key, value: value, options: options);
}
if (cacheInBackground)
_ = Task.Run(() => Cache(), token);
else
Cache();
}
return value;
}
public static async Task<string> GetOrSetAsync(this IDistributedCache cache, string key, Func<Task<string>> factory, DistributedCacheEntryOptions? options = null, bool cacheInBackground = false, CancellationToken token = default)
{
var value = await cache.GetStringAsync(key, token: token);
if(value is null)
{
// create new and save
value = await factory();
Task CacheAsync() => options is null
? cache.SetStringAsync(key: key, value: value, token: token)
: cache.SetStringAsync(key: key, value: value, options: options, token: token);
if (cacheInBackground)
_ = Task.Run(async () => await CacheAsync(), token);
else
await CacheAsync();
}
return value;
}
}
}