Last active
August 20, 2020 01:10
-
-
Save akunzai/2486c8b1bfb5ef172e0c60506bf78479 to your computer and use it in GitHub Desktop.
GetOrCreateAync for IDistributedCache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.IO; | |
| using System.Text.Json; | |
| using System.Threading.Tasks; | |
| namespace Microsoft.Extensions.Caching.Distributed | |
| { | |
| public static class DistributedCacheExtensions | |
| { | |
| public static async Task<T> GetOrCreateAsync<T>(this IDistributedCache cache, | |
| string key, | |
| Func<Task<T>> factory, | |
| DistributedCacheEntryOptions options = null) | |
| { | |
| if (cache == null) | |
| throw new ArgumentNullException(nameof(cache)); | |
| if (key == null) | |
| throw new ArgumentNullException(nameof(key)); | |
| if (factory == null) | |
| throw new ArgumentNullException(nameof(factory)); | |
| T value; | |
| var bytes = await cache.GetAsync(key).ConfigureAwait(false); | |
| if (bytes == null) | |
| { | |
| value = await factory().ConfigureAwait(false); | |
| await cache.SetAsync(key, | |
| JsonSerializer.SerializeToUtf8Bytes(value), | |
| options ?? new DistributedCacheEntryOptions()).ConfigureAwait(false); | |
| } | |
| else | |
| { | |
| using var utf8Json = new MemoryStream(bytes); | |
| value = await JsonSerializer.DeserializeAsync<T>(utf8Json).ConfigureAwait(false); | |
| } | |
| return value; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment