Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET内核中多种类型的分布式缓存_C#_Caching_Asp.net Core_Session State - Fatal编程技术网

C# ASP.NET内核中多种类型的分布式缓存

C# ASP.NET内核中多种类型的分布式缓存,c#,caching,asp.net-core,session-state,C#,Caching,Asp.net Core,Session State,假设我有一个ASP.NETCore2.x应用程序 我希望使用Redis进行标准的IDistributedCache依赖项注入,但使用SQL Server分布式缓存作为会话中间件的支持 这可能吗?如果是这样,您将如何在Startup.cs中进行配置?分布式会话状态存储默认注入IDistributedCache实例。这意味着,如果要将SQL Server分布式缓存用于会话状态,则应将其配置为默认缓存 出于您自己的缓存目的,您可以创建一个“包装器接口”,专门表示Redis缓存(例如IRedisCach

假设我有一个ASP.NETCore2.x应用程序

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


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

分布式会话状态存储默认注入
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;
    }
}
公共接口IRedisDistributedCache:IDistributedCache { } public void配置服务(IServiceCollection服务) { //添加Redis缓存 services.AddDistributedRedisCache(); services.AddSingleton(); //添加SQL Server缓存作为默认缓存机制 AddDistributedSqlServerCache(); } 公共类控制器:控制器 { 私有只读IRedisDistributedCache\u redisCache; 公共FooController(IRedisDistributedCache-redisCache) { _redisCache=redisCache; } }
在这种情况下,您将如何初始化Redis实例?通常,我已经在services.AddDistributedRedisCache()调用中对其进行了初始化。@user1142433请参见代码示例。我正在调用
AddDistributedRedisCache()
,就像您通常会调用的那样,在将
RedisCache
实现绑定到
ireDistributedCache
“包装器接口”之后,您正在向DI服务添加两个IDistributedCache缓存项(一个Redis,一个基于SQL)?当会话调用IDistributedCache实现时,它会得到SQL版本,因为您在Redis版本之后将其添加到服务配置中?换句话说,服务解析器如何决定它将哪个IDistributedCache提供给服务中间件?@user1142433这是正确的。容器将选择您注册的最后一个容器。我现在知道它在原则上应该如何工作。不幸的是,该示例无法编译,因为在line services.AddSingleton()上“没有从RedisCache到IRedisDistributedCache的隐式转换”;