簡體   English   中英

.net core控制台應用程序強類型配置

[英].net core Console application strongly typed Configuration

在.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上運行的控制台應用程序

謝謝!

您需要添加NuGet包Microsoft.Extensions.Configuration.Binder以使其在控制台應用程序中工作。

我最近必須實現這個,所以我想添加一個完整的工作解決方案:

確保安裝了以下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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM