Skip to content

Instantly share code, notes, and snippets.


dcomartin/LazyLoadCache.cs Secret

Created Nov 18, 2020
What would you like to do?
public async Task<Product> GetProduct(Guid productId)
// Step 1: Get Value from Cache
var cacheResult = await _cacheClient.GetAsync<Product>(BuildCacheKey(productId));
if (cacheResult.HasValue)
return cacheResult.Value;
// Step 2: Cache Miss, Fetch from Database
var product = await _dbContext.Products
.Where(x => x.Id == productId)
.Select(x => new Product
Id = x.Id,
Name = x.Name,
// Step 3 - Write to Cache & Expire in 30 minutes
await _cacheClient.SetAsync(BuildCacheKey(productId), product, DateTime.UtcNow.AddMinutes(30));
return product;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.