我正在尝试根据.net核心中的Options pattern使用强类型的json配置设置。到目前为止,所有示例都显示了将强类型设置类注入(inject)到 Controller 中是多么容易,但是我需要在中间件类中使用它(非常类似于this question,但尝试这种方式后,我将不再做进一步的介绍)。
因此,设置:
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>
注入(inject)类构造函数中,以便可以调用 GetName 方法? 最佳答案
几点:
提及的类中缺少
services.AddSingleton<IMysettingsService, MysettingsService >(i => new MysettingsService ());
按着这些次序:
public class MySettings
{
public string Name { get; set; }
public string Description { get; set; }
}
public class MySettingsService : IMySettingsService
{
private readonly MySettings mySettings;
public MySettingsService (IOptions<MySettings> _mySettings)
{
mySettings = _mySettings.Value;
}
public string GetName()
{
return mySettings.Name;
}
}
services.Configure<MySettings>(this.Configuration.GetSection("MySettings"));
services.AddSingleton<IMySettingsService, MySettingsService >();
编辑-我将包括实现以供您遵循
我创建了一个示例应用程序,它对我有用。请按照以下步骤操作:
很少的细节。
我的应用程序名称是:
SettingsApp
mySettings.json
-Startup
中配置它看到这行:
MySettings
对象以保存设置注意:我使用命名空间
SettingsApp.Initialisations
保留此文件。您可以根据您的应用程序结构选择任何一个。IMySettingsService
注意:为此,我使用命名空间
SettingsApp.Services
。IMySettingsService
Startup.ConfigureServices
方法请注意包括所需的用途。
检查以下代码,了解如何完成此操作:
HomeController
进行测试。)