MemoryCache
- Author
- Scott Rickman
- Last updated
- 2026-08-20
Program.cs
namespace RealWebDevelopers;
using Microsoft.Extensions.Caching.Memory;
public class Program
{
public static void Main(string[] args)
{
// ...
builder.Services.AddMemoryCache();
}
}
Provider.cs
namespace RealWebDevelopers;
public class Provider
{
private readonly IMemoryCache memoryCache;
private readonly MemoryCacheEntryOptions memoryCacheEntryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60); // Cache for 1 hour
}
public Provider(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
public IEnumberable<Product> GetProducts()
{
var cacheKey = "product";
if (!this.memoryCache.TryGetValue(cacheKey, out List<Product> productCache))
{
try
{
// Fetch the data from source i.e. Database query
var products = this.session.Query<Product>();
this.memoryCache.Set(cacheKey, products, this.memoryCacheEntryOptions);
return products;
}
catch
{
// Whatever
}
}
return productCache;
}
}