如何将 Microsoft.Extensions.Caching.StackExchangeRedis 的多个实现与 Net Core DI 结合使用?
如何在 net core 中使用多个 redis 实例以及 DI 容器?
在启动时,我有以下内容:
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = distributedCacheConnectionString;
});
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = myAppSessionCacheConnectionString;
});
对于注入,我会在构造函数中包含类似以下内容的内容,例如:
namespace MyApp
{
public class MyClass
{
public MyClass(IDistributedCache myAppSessionCache)
{
// use a specific redis cache instance here
_distributedCache = myAppSessionCache;
}
}
}
namespace MyApp
{
public class MyClass2
{
public MyClass2(IDistributedCache distributedCache)
{
// use a specific redis cache instance here
_distributedCache = distributedCache;
}
}
}
我知道对于网络核心,DI容器与Unity或Spring等相比是有限的...我知道接口的多种实现有几个技巧,一个是注入接口的 IEnumerable,另一个例子是类型化接口,等等...我只是没有看到 redis 缓存的选项,我们确实需要一个应用程序与 2 个独立的通信系统内的redis服务器。
我主要是在寻找阻力最小的路径。我总是可以围绕 Redis 客户端创建一个包装器。我只是希望有什么东西存在,但我只是忽略了它。
How do I use multiple instances of redis in net core along with the DI container?
On startup I have the following:
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = distributedCacheConnectionString;
});
services.AddStackExchangeRedisCache(options =>
{
options.Configuration = myAppSessionCacheConnectionString;
});
For injection I would have something like the following in a constructor for example:
namespace MyApp
{
public class MyClass
{
public MyClass(IDistributedCache myAppSessionCache)
{
// use a specific redis cache instance here
_distributedCache = myAppSessionCache;
}
}
}
namespace MyApp
{
public class MyClass2
{
public MyClass2(IDistributedCache distributedCache)
{
// use a specific redis cache instance here
_distributedCache = distributedCache;
}
}
}
I know for net core the DI container is limited compared something like Unity or Spring etc... I know for multiple implementations of an interface there are several tricks, one is injecting an IEnumerable of the interface, another example is typed interfaces, etc... I just don't see the option with the redis cache and we do have a need for an application to communicate with 2 separate redis servers within the system.
I am mostly looking for the path of least resistance. I can always create a wrapper around the Redis Client. I was just hoping that something existed but I was just overlooking it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要能够区分系统中的两种类型的缓存(一种用于会话,另一种用于普通缓存)。
我认为可以这样做:
然后我们必须实现这些接口。
然后在启动时你可以像这样注册这些服务:
最后,你可以根据你的需要分别使用这两个接口。
I think you need to be able to distinguish between two types of caches in your system (one for session and another for ordinary cache).
I think something like this can be done:
then we have to implement these interfaces.
then in startup you can register these services like this:
Finally, you can use these two interfaces separately based on your needs.