.net core 控制台应用强类型配置 [英] .net core Console application strongly typed Configuration
问题描述
在 .NET Core 控制台应用程序上,我尝试将自定义 appsettings.json 文件中的设置映射到自定义配置类.
On an .NET Core Console app, I'm trying to map settings from a custom appsettings.json file into a custom configuration class.
我在网上查看了几个资源,但无法使 .Bind 扩展方法起作用(我认为它适用于 asp.net 应用程序或以前版本的 .Net Core,因为大多数示例都表明了这一点).
I've looked at several resources online but was not able to get the .Bind extension method work (i think it works on asp.net apps or previous version of .Net Core as most of the examples show that).
代码如下:
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfigurationRoot configuration = builder.Build();
//this is a custom configuration object
Configuration settings = new Configuration();
//Bind the result of GetSection to the Configuration object
//unable to use .Bind extension
configuration.GetSection("MySection");//.Bind(settings);
//I can map each item from MySection manually like this
settings.APIBaseUrl = configuration.GetSection("MySection")["APIBaseUrl"];
//what I wish to accomplish is to map the section to my Configuration object
//But this gives me the error:
//IConfigurationSection does not contain the definition for Bind
//is there any work around for this for Console apps
//or do i have to map each item manually?
settings = configuration.GetSection("MySection").Bind(settings);
//I'm able to get the result when calling individual keys
Console.WriteLine($"Key1 = {configuration["MySection:Key1"]}");
Console.WriteLine("Hello World!");
}
是否有任何方法可以将结果从 GetSection("MySection") 自动映射到自定义对象?这是针对在 .NET Core 1.1 上运行的控制台应用程序
Is there any approach to auto map the results from GetSection("MySection") to a custom object? This is for Console Application running on .NET Core 1.1
谢谢!
推荐答案
您需要添加 NuGet 包 Microsoft.Extensions.Configuration.Binder
以使其在控制台应用程序中工作.
You need to add the NuGet package Microsoft.Extensions.Configuration.Binder
to get it to work in a console application.
这篇关于.net core 控制台应用强类型配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!