将 appsettings.json 读入定义了接口的对象
Read appsettings.json into object that has an interface defined
我需要将自定义设置从 appsettings.json 读取到定义了自定义接口的 POCO 对象中。这段代码有效——但是有更好的方法吗?也许类似于通过 services.Configure 和 IOptions 读取选项?不幸的是,使用 IOptions 是不可能的,因为我正在调用另一个库,该库需要一个实现 'IConfigOptions' 接口的对象。
services.AddSingleton<IConfigOptions>(obj => new ConfigOptions
{
Param1 = Configuration["Options:Param1"],
Param2 = Configuration["Options:Param2"],
Param3 = Configuration["Options:Param3"],
<etc>
});
建议?
这样的?
var config = new MailConfiguration();
_configuration.Bind("Outbox.Email", config);
"Outbox.Email": {
"smtp": "smtp.com",
"port": 587,
"user": "user@user.com",
"from": "user name",
"password": "669855,",
},
在 C# 中 Configuration
中有方法可以自动从应用程序设置中为您读取所有 属性。
如果对象的属性与 JSON 中的名称匹配,那么您可以执行以下操作:
services.AddSingleton<IConfigOptions,ConfigOptions>(_ =>
Configuration
.GetSection(nameof(ConfigOptions))
.Get<ConfigOptions>());
appsettings.json 看起来像:
"ConfigOptions": {
"Param1": "text1",
"Param2": "text2",
"Param3": "text3"
}
ConfigOptions 如下所示:
public class ConfigOptions {
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
在 startup.cs 文件中你应该有配置 属性 例如
public IConfiguration Configuration { get; }
然后您可以编写以下内容:
var modelConfiguration = Configuration
.GetSection("Section")
.Get<YourModel>();
services.AddSingleton(modelConfiguration );
“部分”:代表 app.settings.json 文件中的部分
YourModel :表示 class,它就像 app.settings 部分中参数的容器
services.AddSingleton(modelConfiguration )
: 使用 DI
使其可访问
我需要将自定义设置从 appsettings.json 读取到定义了自定义接口的 POCO 对象中。这段代码有效——但是有更好的方法吗?也许类似于通过 services.Configure 和 IOptions 读取选项?不幸的是,使用 IOptions 是不可能的,因为我正在调用另一个库,该库需要一个实现 'IConfigOptions' 接口的对象。
services.AddSingleton<IConfigOptions>(obj => new ConfigOptions
{
Param1 = Configuration["Options:Param1"],
Param2 = Configuration["Options:Param2"],
Param3 = Configuration["Options:Param3"],
<etc>
});
建议?
这样的?
var config = new MailConfiguration();
_configuration.Bind("Outbox.Email", config);
"Outbox.Email": {
"smtp": "smtp.com",
"port": 587,
"user": "user@user.com",
"from": "user name",
"password": "669855,",
},
在 C# 中 Configuration
中有方法可以自动从应用程序设置中为您读取所有 属性。
如果对象的属性与 JSON 中的名称匹配,那么您可以执行以下操作:
services.AddSingleton<IConfigOptions,ConfigOptions>(_ =>
Configuration
.GetSection(nameof(ConfigOptions))
.Get<ConfigOptions>());
appsettings.json 看起来像:
"ConfigOptions": {
"Param1": "text1",
"Param2": "text2",
"Param3": "text3"
}
ConfigOptions 如下所示:
public class ConfigOptions {
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
在 startup.cs 文件中你应该有配置 属性 例如
public IConfiguration Configuration { get; }
然后您可以编写以下内容:
var modelConfiguration = Configuration
.GetSection("Section")
.Get<YourModel>();
services.AddSingleton(modelConfiguration );
“部分”:代表 app.settings.json 文件中的部分
YourModel :表示 class,它就像 app.settings 部分中参数的容器
services.AddSingleton(modelConfiguration )
: 使用 DI