nop
nop

Reputation: 6331

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

I wanted to pull the configuration from appsettings.json into an object of type ExchangeOptions. I know that configuration.Get<T>() works in ASP.NET Core, but I forgot the correct package for .NET Core Console application. I currently have the following NuGet packages:

The example below is pretty self explanatory.

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();
    }
}

Upvotes: 1

Views: 1376

Answers (1)

nop
nop

Reputation: 6331

The correct package for configuration.Get<ExchangeOptions>() was Microsoft.Extensions.Configuration.Binder. Thanks anyway!

Upvotes: 3

Related Questions