Partial caching
Outline
At a glance
- What it is: Caching reusable fragments like blocks and product cards.
- Why it matters: Reduces rendering time and server load.
- Core APIs: IMemoryCache, IDistributedCache, OutputCache.
- Optimizely advantage: IContentCacheKeyService enables smart invalidation.
- DXP rule: Use distributed caching in multi-node environments.
This module provides a technical deep dive into partial (fragment) caching within ASP.NET Core-based Optimizely solutions.
1. In-Memory Caching (IMemoryCache)
// Program.cs
builder.Services.AddMemoryCache();
public class MyService
{
private readonly IMemoryCache _memoryCache;
public MyService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public string GetCachedData(string key)
{
if (!_memoryCache.TryGetValue(key, out string cachedValue))
{
cachedValue = FetchDataFromDatabase();
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5))
.SetAbsoluteExpiration(TimeSpan.FromMinutes(30));
_memoryCache.Set(key, cachedValue, cacheEntryOptions);
}
return cachedValue;
}
}
2. Distributed Caching (IDistributedCache)
// Program.cs
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("RedisCache");
options.InstanceName = "OptimizelyApp_";
});
public class MyService
{
private readonly IDistributedCache _distributedCache;
public MyService(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public async Task<string> GetCachedDataAsync(string key)
{
byte[] encodedValue = await _distributedCache.GetAsync(key);
string cachedValue;
if (encodedValue != null)
{
cachedValue = Encoding.UTF8.GetString(encodedValue);
}
else
{
cachedValue = await FetchDataFromDatabaseAsync();
byte[] valueToCache = Encoding.UTF8.GetBytes(cachedValue);
var options = new DistributedCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(5))
.SetAbsoluteExpiration(TimeSpan.FromMinutes(30));
await _distributedCache.SetAsync(key, valueToCache, options);
}
return cachedValue;
}
}
