Skip to content

Instantly share code, notes, and snippets.

@akunzai
Last active August 20, 2020 01:10
Show Gist options
  • Select an option

  • Save akunzai/2486c8b1bfb5ef172e0c60506bf78479 to your computer and use it in GitHub Desktop.

Select an option

Save akunzai/2486c8b1bfb5ef172e0c60506bf78479 to your computer and use it in GitHub Desktop.
GetOrCreateAync for IDistributedCache
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