.net ядро Консольное приложение строго типизировано Конфигурация

2

В приложении.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

Спасибо!

Теги:
.net-core

2 ответа

7
Лучший ответ

Вам нужно добавить пакет NuGet Microsoft.Extensions.Configuration.Binder чтобы заставить его работать в консольном приложении.

6

Я должен был реализовать это недавно, поэтому подумал, что я бы добавил целое рабочее решение:

Убедитесь, что установлены следующие пакеты 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; }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню