A persistent cache service stores cached values in durable SQL Server storage, allowing them to survive application restarts. The distributed cache can also be shared by application instances running across servers or containers. section 17.2.2
Create the service by preparing the database, configuring the application, and registering SQL Server caching:
- Install dotnet-sql-cache version 7.0.0 and create the cache table in CacheDb. section 17.2.2
- Store the database connection in appsettings.json under ConnectionStrings:CacheConnection. section 17.2.2
- Register AddDistributedSqlServerCache with the connection string, dbo schema, and DataCache table. section 17.2.2
- Coordinate cache keys carefully when different applications share the database, because each application must read the expected data type. 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();
View the complete Program.cs registration, including configuration lookup, schema, table, and application startup. section 17.2.2
