【发布时间】:2019-02-02 15:58:46
【问题描述】:
假设我有一个 ASP.NET Core 2.x 应用程序。
我想使用 Redis 进行标准的 IDistributedCache 依赖注入,但使用 SQL Server 分布式缓存作为 Session 中间件的支持。
这可能吗?如果是这样,您将如何在Startup.cs 中进行配置?
【问题讨论】:
标签: c# caching asp.net-core session-state
假设我有一个 ASP.NET Core 2.x 应用程序。
我想使用 Redis 进行标准的 IDistributedCache 依赖注入,但使用 SQL Server 分布式缓存作为 Session 中间件的支持。
这可能吗?如果是这样,您将如何在Startup.cs 中进行配置?
【问题讨论】:
标签: c# caching asp.net-core session-state
分布式会话状态存储默认注入IDistributedCache 实例。这意味着如果您想将 SQL Server 分布式缓存用于会话状态,则应将其配置为默认缓存。
为了您自己的缓存目的,您可以创建一个专门表示 Redis 缓存的“包装器接口”(例如 IRedisCache),注册它并将其注入您的中间件/控制器/服务中。例如:
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;
}
}
【讨论】:
AddDistributedRedisCache(),然后将RedisCache 实现绑定到IRedisDistributedCache“包装接口”。