.net核心控制台应用程序强类型配置

时间:2017-09-02 14:38:45

标签: c# .net-core

在.NET Core Console应用上,我尝试将自定义appsettings.json文件中的设置映射到自定义配置类。

我已经在线查看了几个资源,但无法使.Bind扩展方法正常工作(我认为它适用于asp.net应用程序或以前版本的.Net Core,因为大多数示例都显示了这一点)

以下是代码:

 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上运行的控制台应用程序

谢谢!

2 个答案:

答案 0 :(得分:17)

您需要添加NuGet包Microsoft.Extensions.Configuration.Binder才能使其在控制台应用程序中运行。

答案 1 :(得分:13)

我最近必须实现这一点,所以我想添加一个完整的解决方案:

确保安装了以下Nuget软件包:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.Json
  • Microsoft.Extensions.Configuration.Binder

添加json文件并定义一些设置:

AppSettings.json

{
  "Settings": {
    "ExampleString": "StringSetting",
    "Number" :  1
  }
}

将此配置绑定到控制台应用程序中的对象

public class Program
{
    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("AppSettings.json");

        var config = builder.Build();

        var appConfig = config.GetSection("Settings").Get<AppSettings>();

        Console.WriteLine(appConfig.ExampleString);
        Console.WriteLine(appConfig.Number);
    }
}

public class AppSettings
{
    public string ExampleString { get; set; }
    public int Number { get; set; }
}