我使用StackExchange.Redis
添加Redis的連接到.NET的核心,但目前看起來是這樣的:在Startup
在.NET核心依賴注入中`StackExchange.Redis.ConnectionMultiplexer`是'AddStatic`還是`AddScope`?
public void ConfigureServices(IServiceCollection services)
{
services.AddRedisMultiplexer(() =>
ConfigurationOptions.Parse(Configuration["ConnectionStrings:Redis"]));
...
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));
}
那麼這則意味着我可以使用IConnectionMultiplexer
的依賴隨時注射。
我的問題是:ConnectionMultiplexer
是designed to be reused,所以我用AddSingleton
爲整個應用程序保留一個實例。不過,我也可以使用AddScoped
在請求期間使用一個。哪個更好?爲什麼?
該應用程序需要擴展,但我並不期待大量的併發請求。我的意見是也使用'AddSingleton',但我對使用'StackExchange.Redis'還不太瞭解,並且有點不確定複用器的複用程度。 – Keith
@Keith多路複用器似乎甚至只是通過傳遞連接URL來處理多個Redis實例(主/從),所以我認爲這是一個不錯的選擇。 – Niloct