1

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:

  • Microsoft.Extensions.Configuration
  • Microsoft.Extensions.Configuration.FileExtensions
  • Microsoft.Extensions.Configuration.Json

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.