2016-04-28 177 views
1

背景:使用Asp.Net核心網站依賴注入中繼需要服務的網站的各個部分動態更新依賴注入服務

我有被添加到IServiceCollection在ConfigureServices方法在我啓動服務類如下面的方式

//Settings 
services.AddSingleton<ISettingsService, SettingsService>(); 
services.AddSingleton<ISettingsIO, SettingsIO>(); 
services.AddSingleton<ISettings>(f => 
{ 
    return f.GetService<ISettingsService>().GetSettings(); 
}); 

這個偉大的工程,所有的網頁/控制器我需要訪問實例可以這樣做沒有問題。

但是,我現在有能力更改方法GetSettings()中的數據。這意味着我需要更新添加到ServiceCollection的服務。

我該如何做到這一點沒有更改服務從單身到瞬態?

感謝您提供的任何幫助!

+0

GetSettings如何實現? –

+1

我不明白爲什麼'ISetting'也是單身人士,因爲'ISettingsService'已經準備好了。爲什麼不把它用作transient或scoped,並讓單身的'SettingsService'解決它呢? –

+0

@YacoubMassad - GetSiteSettings返回一個ISiteSettings對象,它從查詢創建到數據庫。 – khrave

回答

1

正如我在評論中所說,這不是很乾淨。我認爲更好的解決方案需要更多關於您的系統的信息。

創建一個可變的設置包裝類:

public class MyMutableSettings : ISettings 
{ 
    public ISettings Settings {get;set;} 

    //Implement the ISettings interface by delegating to Settings, e.g.: 
    public int GetNumberOfCats() 
    { 
     return Settings.GetNumberOfCats(); 
    } 
} 

然後你就可以使用它像這樣:

MyMutableSettings mySettings = new MyMutableSettings(); 

services.AddSingleton<ISettings>(f => 
{ 
    mySettings.Settings = f.GetService<ISettingsService>().GetSettings(); 

    return mySettings; 
}); 

然後,當你要更改設置:

mySettings.Settings = GetMyNewSettings();