假设我有一个ASP.NET Core 2.x应用程序 .
我想使用Redis进行标准 IDistributedCache 依赖注入,但使用SQL Server分布式缓存作为Session中间件的支持 .
IDistributedCache
这可能吗?如果是这样,您将如何在 Startup.cs 中进行配置?
Startup.cs
默认情况下,分布式会话状态存储会注入 IDistributedCache 实例 . 这意味着如果要将SQL Server分布式缓存用于会话状态,则应将其配置为默认缓存 .
为了您自己的缓存目的,您可以创建一个"wrapper interface",它专门代表Redis缓存(例如 IRedisCache ),注册它并将其注入您的中间件/控制器/服务中 . 例如:
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; } }
1 回答
默认情况下,分布式会话状态存储会注入
IDistributedCache
实例 . 这意味着如果要将SQL Server分布式缓存用于会话状态,则应将其配置为默认缓存 .为了您自己的缓存目的,您可以创建一个"wrapper interface",它专门代表Redis缓存(例如
IRedisCache
),注册它并将其注入您的中间件/控制器/服务中 . 例如: