using System.Threading.Tasks;
using LazyCache.Providers;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
public class SecurityService
private readonly IAppCache _cache;
public bool ThrowException { get; set; } = true;
ICacheProvider provider = new MemoryCacheProvider(new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions())));
_cache = new CachingService(provider);
public async Task<string> GetTemporalLoginCertificateAsync()
string cert = await _cache.GetOrAddAsync(
async () => await MethodThatCouldThrowAsync().ConfigureAwait(false),
ExpirationMode.LazyExpiration).ConfigureAwait(false);
public async Task<string> MethodThatCouldThrowAsync()
throw new Exception("exception thrown");
return "here is the certificate!!";
public static void Main()
SecurityService service = new SecurityService();
service.ThrowException = true;
Console.WriteLine("throw exception: " + service.ThrowException);
TryLogCertificate(service);
service.ThrowException = false;
Console.WriteLine("throw exception: " + service.ThrowException);
TryLogCertificate(service);
public static void TryLogCertificate(SecurityService service)
string cert = service.GetTemporalLoginCertificateAsync().GetAwaiter().GetResult();
Console.WriteLine(ex.Message);