如何在ASP.NET 5中设置强类型配置? [英] How to set up strongly typed configuration in ASP .NET 5?
问题描述
从第一个链接:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetConfigurationSection("AppSettings"));
services.AddMvc();
}
但是,我没有得到 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 5中设置强类型配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!