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

I am adding a Redis connection to .NET Core with 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 means that I can use IConnectionMultiplexerdependency injection anywhere.

My question is: ConnectionMultiplexer intended for reuse , so I used AddSingletonto save one instance for the whole application. However, I could use AddScopedto use one throughout the request. Which is better and why?

+4
source share
1 answer

? concurrency, , AddScoped .

IMHO , AddSingleton

(...) , ConnectionMultiplexer , , .

redis pub/sub message; , , ConnectionMultiplexer .

, , ConnectionMultiplexer (IMHO).

+5

Source: https://habr.com/ru/post/1662132/


All Articles