2016-11-28 106 views
4

我使用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的依賴隨時注射。

我的問題是:ConnectionMultiplexerdesigned to be reused,所以我用AddSingleton爲整個應用程序保留一個實例。不過,我也可以使用AddScoped在請求期間使用一個。哪個更好?爲什麼?

回答

5

應用程序的預期負載是多少?如果你有很多的併發性,我認爲使用AddScoped意味着爲每個請求啓動和關閉連接會帶來很多不必要的負擔。

而且這些意見恕我直言,說明你應該使用AddSingleton

(...)這是非常罕見,你想簡要地使用 ConnectionMultiplexer,因爲這個想法是重新使用這個對象。

redis的另一個常見用途是作爲pub/sub消息分發工具; 這也很簡單,並且在發生連接失敗的情況下, ConnectionMultiplexer將處理重新訂閱 所有請求通道的細節。

此外,您將節省內存只有一個ConnectionMultiplexer(恕我直言)實例。

+0

該應用程序需要擴展,但我並不期待大量的併發請求。我的意見是也使用'AddSingleton',但我對使用'StackExchange.Redis'還不太瞭解,並且有點不確定複用器的複用程度。 – Keith

+1

@Keith多路複用器似乎甚至只是通過傳遞連接URL來處理多個Redis實例(主/從),所以我認爲這是一個不錯的選擇。 – Niloct