Forked from wahidustoz/IDistributedCache.GetOrCreateAsync.cs
Created
April 16, 2024 04:30
-
-
Save soyprofesor/e1f2baaf38e3c051031f22a1dbcfb66d to your computer and use it in GitHub Desktop.
IDistributedCache GetOrCreateAsync extension method.
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
| public static class DistributedCacheExtensions | |
| { | |
| public static async Task<T?> GetOrCreateAsync<T>( | |
| this IDistributedCache cache, | |
| string key, | |
| Func<DistributedCacheEntryOptions, Task<T>> factory, | |
| CancellationToken cancellationToken = default) | |
| { | |
| var value = await cache.GetStringAsync(key, cancellationToken); | |
| if(string.IsNullOrWhiteSpace(value)) | |
| { | |
| var options = new DistributedCacheEntryOptions(); | |
| var result = await factory(options); | |
| await cache.SetStringAsync(key, JsonSerializer.Serialize(result), options, cancellationToken); | |
| return result; | |
| } | |
| else | |
| { | |
| return JsonSerializer.Deserialize<T>(value); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment