Muh*_*eed 5 asp.net configuration asp.net-core-mvc asp.net-core
我有以下配置设置:
public void ConfigureServices(IServiceCollection services)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
services.Configure<AppSettings>(configuration);
}
public class AppSettings
{
public ChildSettings Child { get; set; }
public string Property { get; set; }
}
public class ChildSettings
{
public string ChildProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的 appSettings.json 如下所示:
{
"Child": {
"ChildProperty": "Value"
}
"Property": "Value"
}
Run Code Online (Sandbox Code Playgroud)
我可以IOptions<AppSettings>很好地注入我的控制器:
public class MyController : Controller
{
public MyController(IOptions<AppSettings> options)
{
ChildSettings appSettings = options.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
它有点旧了,必须下降几个级别才能到达您想要的设置对象。有没有一种方法可以IOptions<ChildSettings>像这样使用:
public class MyController : Controller
{
public MyController(IOptions<ChildSettings> options)
{
ChildSettings appSettings = options.Value;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想直接使用 ChildSettings 而不通过 AppSettings 对象,则必须将 ChildSettings 注册为 DI 配置中的单独条目,如下所示:
services.Configure<ChildSettings>(_configuration.GetSection("AppSettings:ChildSettings"));
但如果您想这样做,也许您可以将 ChildSettings 放在 appsettings.json 文件的根级别?您不需要在名为 AppSettings 的部分中进行设置。
| 归档时间: |
|
| 查看次数: |
2050 次 |
| 最近记录: |