我試圖使用.net核心中的Options pattern強類型json配置設置。到目前爲止,所有示例都顯示了將強類型設置類注入控制器是多麼容易,但我需要在中間件類中使用它(非常類似於this question,但在嘗試這種方法後我沒有進一步前瞻)。將IOptions傳遞到.Net核心中間件類用於json配置檢索
因此,設置:
mysettings.json
{
"MySettings": {
"Name": "Some Name from config",
"Description": "Some Description from config"
}
}
mysettings.cs
public class MySettings
{
public string Name { get; set; } = "Default name";
public string Description { get; set; } = "Default description";
}
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add functionality to inject IOptions<T>
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<MySettings>(Configuration.GetSection("MySettings"));
services.AddSingleton<IMySettingsService, MySettingsService>();
}
MysettingsService.cs
public class MysettingsService : IMysettingsService
{
private MySettings mySettings { get; set; }
public MysettingsService (MySettings _mySettings)
{
mySettings = _mySettings.value;
}
public string GetName()
{
return mySettings.Name;
}
}
如何去實例MysettingsService.cs和注入IOptions<MySettings>
到類的構造函數,所以我可以調用的GetName方法?
感謝FO的幫助,但我已經完成了你所提到的所有步驟。我如何去使用MySettingsservice的實例來調用GetName方法?特別是,如何通過IOptions來滿足構造函數? –
iKnowNothing
如果以上所有內容都已完成 - 並且讓配置知道mysettings.json文件(https://docs.asp.net/en/latest/fundamentals/configuration.html),我會很好奇,知道您得到了什麼作爲結果在** MySettingsService **的構造函數中?把一個調試點放在那裏,讓我們知道什麼是注入的對象? –
謝謝。我只是意識到DI會照顧MySettingsService的構造函數,如果我只是使用它的接口。您徹底的實施幫助。 – iKnowNothing