diff --git a/EnvelopeGenerator.Application/EnvelopeGenerator.Application.csproj b/EnvelopeGenerator.Application/EnvelopeGenerator.Application.csproj index 5cc3a33f..0e120bcb 100644 --- a/EnvelopeGenerator.Application/EnvelopeGenerator.Application.csproj +++ b/EnvelopeGenerator.Application/EnvelopeGenerator.Application.csproj @@ -18,6 +18,9 @@ + + + diff --git a/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs b/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs index 88f8cdce..d8986131 100644 --- a/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs +++ b/EnvelopeGenerator.Application/Extensions/CacheExtensions.cs @@ -1,11 +1,4 @@ using Microsoft.Extensions.Caching.Distributed; -using Microsoft.Extensions.Options; -using Newtonsoft.Json.Linq; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace EnvelopeGenerator.Application.Extensions { @@ -39,5 +32,51 @@ namespace EnvelopeGenerator.Application.Extensions var value = await cache.GetAsync(key); return value is null ? null : new(BitConverter.ToInt64(value, 0)); } + + public static string GetOrCreate(this IDistributedCache cache, string key, Func 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 GetOrCreateAsync(this IDistributedCache cache, string key, Func> 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; + } } } \ No newline at end of file