在 .NET Core 控制台应用程序中获取 appsettings.json 设置到 class 类型的对象中

Getting appsettings.json settings into an object of class type in .NET Core console application

我想将 appsettings.json 中的配置拉入 ExchangeOptions 类型的对象中。我知道 configuration.Get<T>() 在 ASP.NET Core 中工作,但我忘记了 .NET Core 控制台应用程序的正确包。我目前有以下 NuGet 包:

下面的例子很容易解释。

appsettings.json

{
  "ExchangeConfiguration": {
    "Exchange": "Binance",
    "ApiKey": "modify",
    "SecretKey": "modify"
  }
}

Program.cs

using Microsoft.Extensions.Configuration;
using System;

public class ExchangeOptions
{
    public Exchange Exchange { get; set; }
    public string ApiKey { get; set; }
    public string SecretKey { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        IConfiguration configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();
    
        // These work fine
        var exchange = configuration["ExchangeConfiguration:Exchange"];
        var apiKey = configuration["ExchangeConfiguration:ApiKey"];
        var secretKey = configuration["ExchangeConfiguration:SecretKey"];

        // This doesn't work, because I don't have the right NuGet package
        ExchangeOptions exchangeOptions = configuration.Get<ExchangeOptions>();
    
        Console.ReadKey();
    }
}

configuration.Get<ExchangeOptions>() 的正确包裹是 Microsoft.Extensions.Configuration.Binder。无论如何谢谢!