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