.NET Core依赖注入中的StackExchange.Redis.ConnectionMultiplexer应该是AddStatic还是AddScope? [英] Should `StackExchange.Redis.ConnectionMultiplexer` be `AddStatic` or `AddScope` in .NET Core dependency injection?
问题描述
我正在使用 StackExchange.Redis
将Redis连接添加到.NET Core,当前看起来像这样:
I'm adding a Redis connection to .NET Core using StackExchange.Redis
, it currently looks something like this:
public static IServiceCollection AddRedisMultiplexer(
this IServiceCollection services,
Func<ConfigurationOptions> getOptions = null)
{
// Get the options or assume localhost, as these will be set in Startup.ConfigureServices assume they won't change
var options = getOptions?.Invoke() ?? ConfigurationOptions.Parse("localhost");
// The Redis is a singleton, shared as much as possible.
return services.AddSingleton<IConnectionMultiplexer>(provider => ConnectionMultiplexer.Connect(options));
}
然后在 Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddRedisMultiplexer(() =>
ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"]));
...
这意味着我可以使用 IConnectionMultiplexer
用于在任何地方进行依赖项注入。
This then means I can use IConnectionMultiplexer
for the dependency injection anywhere.
我的问题是: ConnectionMultiplexer
是旨在重复使用,所以我使用了 AddSingleton
为整个应用程序保留一个实例。但是,我也可以使用 AddScoped
在请求期间使用一个。哪个更好?为什么?
My question is: ConnectionMultiplexer
is designed to be reused, so I've used AddSingleton
to keep a single instance for the entire application. However I could also use AddScoped
to use one for the duration of the request. Which is better and why?
推荐答案
应用程序的预期负载是多少?如果您有很多并发性,我认为使用 AddScoped
意味着很多不必要的负担来启动和关闭每个请求的连接。
What is the load expected to the app ? If you have much concurrency, I think using AddScoped
would mean a lot of unnecessary burden to initiate and close connections for every request.
此外,恕我直言,这些观察结果还表明您应该使用 AddSingleton
Also these observations IMHO show that you should use AddSingleton
(...)很少使用
ConnectionMultiplexer,因为这种想法是要重用此对象。
(...) it is exceptionally rare that you would want to use a ConnectionMultiplexer briefly, as the idea is to re-use this object.
redis的另一个常见用法是作为发布/订阅消息分发工具;
这也很简单,并且在连接失败的情况下,
ConnectionMultiplexer将处理重新订阅请求的频道
的所有详细信息。
Another common use of redis is as a pub/sub message distribution tool; this is also simple, and in the event of connection failure, the ConnectionMultiplexer will handle all the details of re-subscribing to the requested channels.
此外,您将只拥有一个 ConnectionMultiplexer
(IMHO)实例来节省内存。
Also, you will save memory having only one instance of ConnectionMultiplexer
(IMHO).
这篇关于.NET Core依赖注入中的StackExchange.Redis.ConnectionMultiplexer应该是AddStatic还是AddScope?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!