Skip to content

Instantly share code, notes, and snippets.

@wahidustoz
Created April 15, 2024 18:33
Show Gist options
  • Select an option

  • Save wahidustoz/4e09c41b94b65de70c9beb3b531415f0 to your computer and use it in GitHub Desktop.

Select an option

Save wahidustoz/4e09c41b94b65de70c9beb3b531415f0 to your computer and use it in GitHub Desktop.
IDistributedCache GetOrCreateAsync extension method.
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