关于 c#:ASP.NET Core 中的多种分布式缓存

Multiple types of Distributed Cache in ASP.NET Core

假设我有一个 ASP.NET Core 2.x 应用程序。

我想使用 Redis 进行标准的 IDistributedCache 依赖注入,但使用 SQL Server 分布式缓存作为会话中间件的支持。

这可能吗?如果是这样,您将如何在 Startup.cs 中配置它?


分布式会话状态存储默认注入IDistributedCache实例。这意味着如果您想将 SQL Server 分布式缓存用于会话状态,则应将其配置为默认缓存。

出于您自己的缓存目的,您可以创建一个专门代表 Redis 缓存的"package器接口"(例如 IRedisCache),注册它并将其注入您的中间件/控制器/服务中。例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public interface IRedisDistributedCache : IDistributedCache
{
}

public void ConfigureServices(IServiceCollection services)
{
    // Add Redis caching
    services.AddDistributedRedisCache();
    services.AddSingleton<IRedisDistributedCache, RedisCache>();

    // Add SQL Server caching as the default cache mechanism
    services.AddDistributedSqlServerCache();
}

public class FooController : Controller
{
    private readonly IRedisDistributedCache _redisCache;

    public FooController(IRedisDistributedCache redisCache)
    {
        _redisCache = redisCache;
    }
}