.NET Core 依赖注入中的`StackExchange.Redis.ConnectionMultiplexer` 应该是`AddSingleton` 还是`AddScope`? [英] Should `StackExchange.Redis.ConnectionMultiplexer` be `AddSingleton` or `AddScope` in .NET Core dependency injection?

查看:63
本文介绍了.NET Core 依赖注入中的`StackExchange.Redis.ConnectionMultiplexer` 应该是`AddSingleton` 还是`AddScope`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 StackExchange.Redis 添加到 .NET Core 的 Redis 连接,它目前看起来像这样:

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 实例(恕我直言),您将节省内存.

Also, you will save memory having only one instance of ConnectionMultiplexer (IMHO).

这篇关于.NET Core 依赖注入中的`StackExchange.Redis.ConnectionMultiplexer` 应该是`AddSingleton` 还是`AddScope`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆