在其他选项中绑定选项 services.Configure<>()
Binding options inside other options services.Configure<>()
假设我在 appsettings.json 中有以下设置:
{
"OtherSettings" : {
"id" : 3
},
"Needed" : {
"Database" : {
"ConnectionString" : "abc123"
},
"Interval" : {
"is_active" = true,
"in_seconds" = "15"
}
}
}
对于数据库部分,我有一个 class,它是 DatabaseSettings
和 属性 ConnectionString
。
对于间隔部分,我有 class IntervalSettings
。
如果我想将 Needed
中的所有这些设置绑定到 class NeededSettings
,我需要什么 属性 以及如何绑定选项具有依赖注入的数据库 class ?目前我正在这样做:
services.Configure<DatabaseSettings>Configuration.GetSection("Needed:Database"));
services.Configure<IntervalSettings>(Configuration.GetSection("Needed:Interval"));
所以我用 2 行来做这个,但我想用 1 行来做并将所有设置绑定到新的 class NeededSettings
只需删除这两行并添加:
services.Configure<NeededSettings>(Configuration.GetSection("Needed"));
并在所有使用 DatabaseSettings
和 IntervalSetttings
的地方使用 NeededSettings
。
编辑:
public class NeededSettings{
public DatabaseSettings Database {get;set;}
public IntervalSettings Interval {get;set;}
}
假设我在 appsettings.json 中有以下设置:
{
"OtherSettings" : {
"id" : 3
},
"Needed" : {
"Database" : {
"ConnectionString" : "abc123"
},
"Interval" : {
"is_active" = true,
"in_seconds" = "15"
}
}
}
对于数据库部分,我有一个 class,它是 DatabaseSettings
和 属性 ConnectionString
。
对于间隔部分,我有 class IntervalSettings
。
如果我想将 Needed
中的所有这些设置绑定到 class NeededSettings
,我需要什么 属性 以及如何绑定选项具有依赖注入的数据库 class ?目前我正在这样做:
services.Configure<DatabaseSettings>Configuration.GetSection("Needed:Database"));
services.Configure<IntervalSettings>(Configuration.GetSection("Needed:Interval"));
所以我用 2 行来做这个,但我想用 1 行来做并将所有设置绑定到新的 class NeededSettings
只需删除这两行并添加:
services.Configure<NeededSettings>(Configuration.GetSection("Needed"));
并在所有使用 DatabaseSettings
和 IntervalSetttings
的地方使用 NeededSettings
。
编辑:
public class NeededSettings{
public DatabaseSettings Database {get;set;}
public IntervalSettings Interval {get;set;}
}