ASP.NET Core 2 - 多个Azure Redis缓存服务DI

use*_*430 15 c# dependency-injection asp.net-core asp.net-core-2.0

在ASP.NET Core 2中,我们可以像这样添加Azure Redis缓存:

 services.AddDistributedRedisCache(config =>
 {
    config.Configuration = Configuration.GetConnectionString("RedisCacheConnection");
    config.InstanceName = "MYINSTANCE";
 });
Run Code Online (Sandbox Code Playgroud)

那么用法将是这样的:

private readonly IDistributedCache _cache;

public MyController(IDistributedCache cache)
{
   _cache = cache;
}
Run Code Online (Sandbox Code Playgroud)

我该怎么办才能拥有:

private readonly IDistributedCache _cache1;
private readonly IDistributedCache _cache2;

public MyController(IDistributedCache cache1, IDistributedCache cache2)
{
   _cache1 = cache1;
   _cache2 = cache2;
}
Run Code Online (Sandbox Code Playgroud)

我的问题如何添加另一个指向不同的Azure Redis缓存连接和实例的服务,并在我想使用它们时将它们分开?

Cod*_*ler 13

在场景后面,AddDistributedRedisCache()扩展方法执行以下操作(github上的代码):

  1. 注册要配置的操作RedisCacheOptions.您传递给Lambda AddDistributedRedisCache()负责.实例RedisCacheOptions传递给RedisCache包装的构造函数IOptions<T>.
  2. 寄存器Singletone实现RedisCacheIDistributedCache接口.

不幸的是,这两种行为都不适合你的要求.只能注册一个操作来配置特定类型的选项..net核心依赖注入的本机实现不支持注册覆盖.

仍然有一个解决方案,可以做你想要的.然而这个解决方案有点让我伤心

诀窍是您从RedisCacheOptions继承自定义RedisCacheOptions1,RedisCacheOptions2并为它们注册不同的配置.

然后定义从IDistributedCache继承的自定义IDistributedCache1和IDistributedCache2接口.

最后,您定义了类RedisCache1(它继承了RedisCache的实现,并实现了IDistributedCache1)和RedisCache2(相同).

像这样的东西:

public interface IDistributedCache1 : IDistributedCache
{
}

public interface IDistributedCache2 : IDistributedCache
{
}

public class RedisCacheOptions1 : RedisCacheOptions
{
}

public class RedisCacheOptions2 : RedisCacheOptions
{
}

public class RedisCache1 : RedisCache, IDistributedCache1
{
    public RedisCache1(IOptions<RedisCacheOptions1> optionsAccessor) : base(optionsAccessor)
    {
    }
}

public class RedisCache2 : RedisCache, IDistributedCache2
{
    public RedisCache2(IOptions<RedisCacheOptions2> optionsAccessor) : base(optionsAccessor)
    {
    }
}

public class MyController : Controller
{
    private readonly IDistributedCache _cache1;
    private readonly IDistributedCache _cache2;

    public MyController(IDistributedCache1 cache1, IDistributedCache2 cache2)
    {
        _cache1 = cache1;
        _cache2 = cache2;
    }
}

//  Bootstrapping

services.AddOptions();

services.Configure<RedisCacheOptions1>(config =>
{
    config.Configuration = Configuration.GetConnectionString("RedisCacheConnection1");
    config.InstanceName = "MYINSTANCE1";
});
services.Configure<RedisCacheOptions2>(config =>
{
    config.Configuration = Configuration.GetConnectionString("RedisCacheConnection2");
    config.InstanceName = "MYINSTANCE2";
});

services.Add(ServiceDescriptor.Singleton<IDistributedCache1, RedisCache1>());
services.Add(ServiceDescriptor.Singleton<IDistributedCache2, RedisCache2>());
Run Code Online (Sandbox Code Playgroud)

  • 我的意思是它需要更多的努力它应该:( (3认同)