'Using separate tables for session and cache data in ASP.NET Core

In Asp.Net Core, the session functionality added with a call to IServicesCollection.AddSession() uses whatever backing store is registered for IDistributedCache.

The following call sets up an IDistributedCache using SQL server as the backing store:

// Register IDistributedCache implementation
builder.Services.AddDistributedSqlServerCache(o =>
{
     o.ConnectionString = sqlConnectionString;
     o.SchemaName = "dbo";
     o.TableName = "SessionTable";
});

// Register Sessions
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromSeconds(600);
});

There are instances in the application where I use IDistributedCache in a context outside of sessions.

How can I use separate SQL tables for Session data vs. ad-hoc distributed cache data?

The goal is to be able to clear ad-hoc distributed cache data without affecting session data. In other words, when I inject an instance of IDistributedCache I want it stored in one table, but when I access HttpContext.Session I want it stored in a different table/server.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source