A distributed cache is used in an application to enhance performance and scalability by storing data in memory across multiple servers, thereby reducing database load and lowering latency. It provides high availability and fault tolerance by replicating data and distributing the load, which is crucial for high-traffic applications such as e-commerce sites and streaming services.
Today, I will demonstrate a distributed cache using a .NET Core application that allows the distributed cache to use a SQL Server database as its backing store.
Now I will show a step-by-step process to add a distributed cache to the application.
Step 1: Create the SQL Server Cache Table
Create the SQL Server Cache item table in SQL Server. To do so, you have to use the SQL-Cache tool. This tool creates a table with the name and schema that you specify. Install the SQL-Cache tool by running the following command using .NET CLI
dotnet tool install --global dotnet-sql-cache
Create a table in SQL Server by running the sql-cache create command using .NET CLI.
dotnet sql-cache create "Server=localhost;Database=DB;User Id=sa;Password=****; Encrypt=True;" dbo CacheTable
Provide the SQL Server instance (Server), database (Database), User Id (Your DB User Id), Password(Your DB Password), schema (for example, dbo), and table name (for example, CacheTable):
A message logged in the console:
Table and index were created successfully
This creates a table named CacheTable in your database with the following schema.

Step 2: Install Required NuGet Package
Now you have to add a package to your application from the NuGet package manager using the following command of .NET CLI.
dotnet add package Microsoft.Extensions.Caching.SqlServer
Step 3: Configure Distributed Cache in Program.cs
Register to connect the table in the application by adding the following line of code in the Program.cs
builder.Services.AddDistributedSqlServerCache(options =>
{
options.ConnectionString = builder.Configuration.GetConnectionString("DefaultConnection");
options.SchemaName = "dbo";
options.TableName = "CacheTable";
});
Now you can inject IDistributedCache anywhere (service, controller, or class) in your application.
Step 4: Implement Distributed Cache in a Service Class
Inject into a service class to demonstrate its usage
public class ProductService
{
private readonly IDistributedCache _cache;
public ProductService(IDistributedCache cache)
{
_cache = cache;
}
public async Task SetProductAsync(string productId, string productJson)
{
var options = new DistributedCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30), // expire after 30 minutes
SlidingExpiration = TimeSpan.FromMinutes(10) // refresh expiration if accessed
};
await _cache.SetStringAsync(productId, productJson, options);
}
public async Task GetProductAsync(string productId)
{
return await _cache.GetStringAsync(productId);
}
}
Call the Service class and use it in controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController: ControllerBase
{
private readonly ProductService _productService;
public ProductsController(ProductService productService)
{
_productService = productService;
}
[HttpGet("{id}")]
public async Task Get(string id)
{
var cached = await _productService.GetProductAsync(id);
if (cached != null)
{
return Ok(new { source = "cache", data = cached });
}
// Simulate fetching from DB
var dbData = $"{{ \"id\": \"{id}\", \"name\": \"Sample Product\" }}";
await _productService.SetProductAsync(id, dbData);
return Ok(new { source = "db", data = dbData });
}
}