[英]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. 本文和其他文章展示了如何将您的应用程序设置映射到ASP.NET 5中的类。
From the first link: 从第一个链接:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
services.AddMvc();
}
However, I'm not getting the Configure()
method on services
. 但是,我没有在services
上获得Configure()
方法。 So either I'm missing a package, or the API has changed. 因此,我丢失了一个程序包,或者API更改了。 Which is it? 哪有
I'm using RC1. 我正在使用RC1。 I believe the articles are based on beta 4. 我相信这些文章基于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;
}
If I want to override any of the default values I can add this in my appsettings.json: 如果我想覆盖任何默认值,可以将其添加到我的appsettings.json中:
"UIOptions": {
"DefaultPageSize_SiteList" : "5"
}
But if I'm not changing anything it doesn't matter if this exists in the appsettings.json file. 但是,如果我没有更改任何内容,则是否存在于appsettings.json文件中并不重要。
In startup I have this: 在启动时我有这个:
services.Configure<UIOptions>(Configuration.GetSection("UIOptions"));
In a controller where I need the options injected I have a constructor dependency on 在需要注入选项的控制器中,我对构造函数有依赖性
IOptions<UIOptions>
Note that I get my UIOptions instance from the .Value property of the IOptions 请注意,我从IOptions的.Value属性获取UIOptions实例。
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;
}
Make sure you're using the Microsoft.Extensions.DependencyInjection package. 确保您使用的是Microsoft.Extensions.DependencyInjection程序包。 The package names were changes somewhere around beta8 程序包名称在beta8附近进行了更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.