liveBook · Manning

Persistent cache service

As explained in Pro ASP.NET Core 7, Tenth Edition

A persistent cache service is a cache service that stores cached values in durable storage so they survive application restarts.

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

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains database preparation, package installation, configuration, registration, and cache options without detailing cache internals.
Examples
Uses LocalDB commands, CacheDb, DataCache, appsettings.json, and AddDistributedSqlServerCache in Program.cs.
What it assumes
Assumes access to a SQL Server-compatible database and application configuration while providing the database and cache setup steps.
What you can do after
Operate/configure a shared SQL Server cache using dotnet-sql-cache and Microsoft.Extensions.Caching.SqlServer.
How it connects
Connects distributed caching with SQL Server, connection strings, JSON configuration, and shared application deployments.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.