在.NET Core依赖项注入中,StackExchange.Redis.ConnectionMultiplexer应该是AddSingleton还是AddScope?

编程入门 行业动态 更新时间:2024-10-24 05:17:17
本文介绍了在.NET Core依赖项注入中,StackExchange.Redis.ConnectionMultiplexer应该是AddSingleton还是AddScope?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用 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)); }

然后在启动

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应该是AddSingleton还是AddSc

本文发布于:2023-11-15 21:22:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598058.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应该是   StackExchange   NET   Core   Redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!