如何在ASP.NET Core中设置强类型配置? [英] How to set up strongly typed configuration in ASP.NET Core?
问题描述
本文和
This article and this other article show how you can map your appsettings to a class in ASP.NET 5.
从第一个链接开始:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
services.AddMvc();
}
但是,我没有在services
上使用Configure()
方法.因此,我丢失了一个程序包,或者API更改了.是哪一个?
However, I'm not getting the Configure()
method on services
. So either I'm missing a package, or the API has changed. Which is it?
我正在使用RC1.我相信这些文章是基于beta 4的.
I'm using RC1. I believe the articles are based on beta 4.
推荐答案
此示例将为您提供所需的内容.我有这个课:
This example should give you what you need. I have this class:
public class UIOptions
{
public UIOptions()
{ }
public int DefaultPageSize_SiteList { get; set; } = 10;
public int DefaultPageSize_CountryList { get; set; } = 10;
public int DefaultPageSize_StateList { get; set; } = 10;
public int DefaultPageSize_RoleList { get; set; } = 10;
public int DefaultPageSize_RoleMemberList { get; set; } = 10;
public int DefaultPageSize_UserList { get; set; } = 10;
public int DefaultPageSize_LogView { get; set; } = 10;
}
如果我想覆盖任何默认值,可以将其添加到我的appsettings.json中:
If I want to override any of the default values I can add this in my appsettings.json:
"UIOptions": {
"DefaultPageSize_SiteList" : "5"
}
但是,如果我不进行任何更改,则在appsettings.json文件中是否存在无关紧要.
But if I'm not changing anything it doesn't matter if this exists in the appsettings.json file.
在启动时我有这个:
services.Configure<UIOptions>(Configuration.GetSection("UIOptions"));
在需要注入选项的控制器中,我对
In a controller where I need the options injected I have a constructor dependency on
IOptions<UIOptions>
请注意,我从IOptions的.Value属性获取了UIOptions实例
Note that I get my UIOptions instance from the .Value property of the IOptions
using Microsoft.Extensions.OptionsModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
public class CoreDataController : Controller
{
public CoreDataController(
IOptions<UIOptions> uiOptionsAccessor
)
{
uiOptions = uiOptionsAccessor.Value;
}
private UIOptions uiOptions;
}
这篇关于如何在ASP.NET Core中设置强类型配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!