With ASP.NET Core 9.0, we have access to a new Caching API: HybridCache, and it's designed to replace both IDistributedCache and IMemoryCache.
Let's go through with an example code.
I have the following code:
public interface IDataService
{
Task<ConfigurationData> GetConfigurationData(CancellationToken cancellationToken = default);
}
public abstract class DataServiceBase : IDataService
{
protected const string CacheKey = "configuration-cache-key";
public abstract Task<ConfigurationData> GetConfigurationData(CancellationToken cancellationToken = default);
protected async Task<ConfigurationData> GetConfigurationFromSource(CancellationToken cancellationToken = default)
{
return await Task.FromResult(new ConfigurationData
{
SomeConfig1 = "Some Config1",
SomeConfig2 = "Some Config2"
});
}
}
public class DataServiceWithIDistributedCache(IDistributedCache distributedCache)
: DataServiceBase
{
public async override Task<ConfigurationData> GetConfigurationData(CancellationToken cancellationToken = default)
{
byte[]? bytes = await distributedCache.GetAsync(CacheKey, cancellationToken); // Try to get from cache.
// Cache hit; return the deserialized data.
if (bytes is not null)
{
return JsonSerializer.Deserialize<ConfigurationData>(bytes)!;
}
// Cache miss; get the data from the real source and cache it.
ConfigurationData configurationData = await GetConfigurationFromSource(cancellationToken);
bytes = JsonSerializer.SerializeToUtf8Bytes(configurationData);
await distributedCache.SetAsync(CacheKey, bytes, cancellationToken);
return configurationData;
}
}
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "<ConnectionString>";
});
builder.Services.AddScoped<IDataService, DataServiceWithIDistributedCache>();
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="9.0.0-preview.7.24406.2" />
public class DataServiceWithHybridCache(HybridCache hybridCache)
: DataServiceBase
{
public async override Task<ConfigurationData> GetConfigurationData(CancellationToken cancellationToken = default)
{
return await hybridCache.GetOrCreateAsync(
CacheKey, factory: async token => await GetConfigurationFromSource(token),
cancellationToken: cancellationToken
);
}
}
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = "<ConnectionString>";
});
builder.Services.AddScoped<IDataService, DataServiceWithHybridCache>();
builder.Services.AddHybridCache(options =>
{
// TODO: customize options if required
});
- A factory method.
- State, and a factory method.
Happy Coding.