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)
{
var options = getOptions?.Invoke() ?? ConfigurationOptions.Parse("localhost");
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?
Keith source
share