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;
}
} |
- 在这种情况下,您将如何初始化 Redis 实例?通常,我已经在 services.AddDistributedRedisCache() 调用中对其进行了初始化。
-
@user1142433 查看代码示例。我正在像往常一样调用 AddDistributedRedisCache(),并且将 RedisCache 实现绑定到 IRedisDistributedCache "wrapper interface"。
-
所以您要向 DI 服务添加两个 IDistributedCache 缓存项(一个基于 Redis,一个基于 SQL)?当 Session 调用 IDistributedCache 实现时,它会获取 SQL 版本,因为您在 Redis 版本之后将其添加到服务配置中?换句话说,服务解析器如何决定将哪个 IDistributedCache 提供给服务中间件?
-
@user1142433 是正确的。容器将选择您注册的最后一个。
-
我现在明白原则上它应该如何工作。不幸的是,该示例将无法编译,因为在线服务上"没有从 RedisCache 到 IRedisDistributedCache 的隐式转换"。AddSingleton<IRedisDistributedCache, RedisCache>();
-
@user1142433 抱歉,我忽略了这一点。您可以改为将 RedisCache 注册为服务和实现(例如 AddSingleton<RedisCache>() 并注入 RedisCache 实例。请告诉我它是否有效。