Distributed caching stores cached data where multiple ASP.NET Core application instances can use it. The name of AddDistributedMemoryCache is misleading: its entries live inside one process, are not shared across servers or containers, and disappear when that process stops. AddDistributedSqlServerCache instead stores entries in a SQL Server database that instances can share and that persists across restarts. section 17.2.2
To use a SQL Server cache:
- Create a database, then create its cache table with dotnet sql-cache create. A separate CacheDb database and dbo.DataCache table are one workable setup. section 17.2.2
- Install Microsoft.Extensions.Caching.SqlServer, put the database connection string in appsettings.json, and register AddDistributedSqlServerCache in Program.cs. Set ConnectionString, SchemaName, and TableName to match the table you created. section 17.2.2
Listing 17.13 Using a persistent data cache in the Program.cs file in the Platform folder
var builder = WebApplication.CreateBuilder(args);
//builder.Services.AddDistributedMemoryCache(opts => {
// opts.SizeLimit = 200;
//});
builder.Services.AddDistributedSqlServerCache(opts => {
opts.ConnectionString
= builder.Configuration["ConnectionStrings:CacheConnection"];
opts.SchemaName = "dbo";
opts.TableName = "DataCache";
});
var app = builder.Build();
app.MapEndpoint<Platform.SumEndpoint>("/sum/{count:int=1000000000}");
app.MapGet("/", async context => {
await context.Response.WriteAsync("Hello World!");
});
app.Run();
The Program.cs listing shows the service registration and the three settings that connect the application to the SQL cache table. section 17.2.2
For rendered Razor content, use <distributed-cache> instead of the memory-based <cache> element when application servers must use the same cached content. It accepts the same cache attributes, including expiration and request-based variation. A shared, persistent cache still needs an appropriate backing store; the in-process memory provider does not become shared merely because its registration method contains “Distributed.” section 26.6 section 17.2.2
Check what content caching changes
Put one timestamp inside a <cache> element and another outside it, then reload the page. The cached timestamp stays unchanged while the uncached one updates. This demonstrates content caching, not cross-server sharing; switch to <distributed-cache> with a shared cache to address that need. Enable caching only for a defined performance problem, since cached content can be mixed with newer content. section 26.6



