Should `StackExchange.Redis.ConnectionMultiplexer` be `AddStatic` or `AddScope` in .NET Core dependency injection?

倾然丶 夕夏残阳落幕 提交于 2019-12-07 03:26:38

问题


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));
}

Then in Startup

public void ConfigureServices(IServiceCollection services)
{
    services.AddRedisMultiplexer(() => 
        ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"]));
    ...

This then means I can use IConnectionMultiplexer for the dependency injection anywhere.

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?


回答1:


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.

Also these observations IMHO show that you should use AddSingleton

(...) it is exceptionally rare that you would want to use a ConnectionMultiplexer briefly, as the idea is to re-use this object.

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.

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



来源:https://stackoverflow.com/questions/40844665/should-stackexchange-redis-connectionmultiplexer-be-addstatic-or-addscope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!