Created
April 15, 2024 18:33
-
-
Save wahidustoz/4e09c41b94b65de70c9beb3b531415f0 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