Multi-level caching implementation building on and extending IDistributedCache
$ dotnet add package Microsoft.Extensions.Caching.HybridThis package contains a concrete implementation of the HybridCache API,
simplifying and enhancing cache usage that might previously have been built on top of IDistributedCache.
Key features:
IDistributedCache - all existing cache backends (Redis, SQL Server, CosmosDB, etc) should work immediatelyIBufferDistributedCache APIFull HybridCache documentation is here.
See learn.microsoft.com for full discussion of HybridCache.
From the command-line:
dotnet add package Microsoft.Extensions.Caching.Hybrid
Or directly in the C# project file:
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Hybrid" Version="[CURRENTVERSION]" />
</ItemGroup>
The HybridCache service can be registered and configured via IServiceCollection, for example:
builder.Services.AddHybridCache(/* optional configuration /*);
Note that in many cases you may also wish to register a distributed cache backend, as ; for example a Redis instance:
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("MyRedisConStr");
});
Once registered, the HybridCache instance can be obtained via dependency-injection, allowing the
GetOrCreateAsync API to be used to obtain data:
public class SomeService(HybridCache cache)
{
private HybridCache _cache = cache;
public async Task<SomeDataType> GetSomeInfoAsync(string name, int id, CancellationToken token = default)
{
return await _cache.GetOrCreateAsync(
$"{name}-{id}", // Unique key to the cache entry
async cancel => await GetDataFromTheSourceAsync(name, id, cancel),
cancellationToken: token
);
}
private async Task<SomeDataType> GetDataFromTheSourceAsync(string name, int id, CancellationToken token)
{
// talk to the underlying data store here - could be SQL, gRPC, HTTP, etc
}
}
Additional usage guidance - including expiration, custom serialization support, and alternate usage to reduce delegate allocation - is available on learn.microsoft.com.