Skip to main content

Caching Strategies

In-Memory Cache

builder.Services.AddMemoryCache();

public class ProductService
{
private readonly IMemoryCache _cache;

public async Task<Product> GetByIdAsync(int id)
{
return await _cache.GetOrCreateAsync($"product_{id}", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return await _context.Products.FindAsync(id);
});
}
}

Distributed Cache (Redis)

builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "localhost:6379";
});

public class CacheService
{
private readonly IDistributedCache _cache;

public async Task\<T\> GetOrSetAsync\<T\>(string key, Func<Task\<T\>> factory)
{
var cached = await _cache.GetStringAsync(key);
if (cached != null)
return JsonSerializer.Deserialize\<T\>(cached);

var value = await factory();
await _cache.SetStringAsync(key, JsonSerializer.Serialize(value),
new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
return value;
}
}

Output Caching

builder.Services.AddOutputCache();

app.MapGet("/api/products", GetProducts)
.CacheOutput(policy => policy.Expire(TimeSpan.FromMinutes(5)));