Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Created May 21, 2023 11:59
Show Gist options
  • Save AndyButland/bd161b182431888df09a2a9681f75056 to your computer and use it in GitHub Desktop.
Save AndyButland/bd161b182431888df09a2a9681f75056 to your computer and use it in GitHub Desktop.
public static class DistributedCacheExtensions
{
public static async Task<T?> GetAsync<T>(this IDistributedCache cache, string key)
{
var val = await cache.GetAsync(key);
if (val == null || val.Length == 0)
{
return default;
}
T? result = JsonSerializer.Deserialize<T>(val);
return result;
}
public static async Task SetAsync<T>(this IDistributedCache cache, string key, T value) =>
await SetAsync(cache, key, value, new DistributedCacheEntryOptions());
public static async Task SetAsync<T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options)
{
var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(value));
await cache.SetAsync(key, bytes, options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment