ASP.NET睿2 - 多Azure的Redis的缓存服务DI
在ASP.NET的Core 2我们可以添加一个Azure的Redis的缓存是这样的:ASP.NET睿2 - 多Azure的Redis的缓存服务DI
services.AddDistributedRedisCache(config =>
{
config.Configuration = Configuration.GetConnectionString("RedisCacheConnection");
config.InstanceName = "MYINSTANCE";
});
然后使用将是这样的:
private readonly IDistributedCache _cache;
public MyController(IDistributedCache cache)
{
_cache = cache;
}
我怎么能做到这一点,让我有:
private readonly IDistributedCache _cache1;
private readonly IDistributedCache _cache2;
public MyController(IDistributedCache cache1, IDistributedCache cache2)
{
_cache1 = cache1;
_cache2 = cache2;
}
我的问题,我怎么能添加指向不同的Redis Azure的另一个缓存服务当我想要使用它们时,连接和实例并将它们分开?
幕后,AddDistributedRedisCache()
扩展方法执行以下操作(code on github):
- 寄存器操作以配置
RedisCacheOptions
。您传递给AddDistributedRedisCache()
的Lambda对此负责。RedisCacheOptions
的实例传递给RedisCache
的构造函数,包装成IOptions<T>
。 - 注册单点执行
RedisCache
IDistributedCache
接口。
不幸的是,这两种行为都不适合您的要求。 只能配置一个动作来配置特定类型的选项。 本地执行.net核心依赖注入does not support注册覆盖。
仍然有一个解决方案,将做你想做的。然而这个解决方案有点让我失望
诀窍是您从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>());
我其实和你一样。你是什么意思:“然而这个解决方案有点杀我”?我没有看到这种方法有什么问题,我认为会正常工作 – user2818430
我的意思是它需要更多的努力,它应该:( – CodeFuller
这种先进的方案是不使用默认的'IDistributedCache'做法确实管理。您应该使用像[CacheManager](http://cachemanager.michaco.net/)这样的库,它允许您根据类型参数定义不同的缓存。 –
一个潜在的选择是使用[策略模式](https://stackoverflow.com/a/46597099)来选择要在运行时使用的缓存。 – NightOwl888