I'd like to access the appsettings.json file (and perhaps other config files) using strongly typed classes. There is a lot of info out there about doing so in .NET Core 1 (eg. https://weblog.west-wind.com/posts/2016/may/23/strongly-typed-configuration-settings-in-aspnet-core), but next to nothing about .NET Core 2.
In addition, I'm building a console app, not ASP.NET.
It appears that the configuration API has completely changed in .NET Core 2. I can't work it out. Anyone?
EDIT: I think perhaps the Core 2 docs have not caught up yet. Example: https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationbinder?view=aspnetcore-2.0 indicates, you would think, that ConfigurationBinder exists in .NET Core 2, but an object browser search of Microsoft.Extensions.Configuration and Microsoft.Extensions.Options reveals nothing.
I have used the NuGet Console to
- Install-Package Microsoft.Extensions.Options -Version 2.0.0
- Install-Package Microsoft.Extensions.Configuration -Version 2.0.0
Thanks to Martin Ullrich for that observation, which led to the solution. There were several things at play here:
Microsoft.Extensions.Configurationpackage would install the child namespace DLLs. In fact there are many packages for those in the NuGet Gallery (see here). The NuGet console doesn't tell you what DLLs you're getting specifically, but you can see them in the Solution Browser once they're installed:AND, searching for ConfigurationBinder in the API Browser yields nothing, I'm guessing because it's part of the extension library.
So, in summary, the solution was to:
the first giving the
.Bindmethod, and the second the.SetBasePathand.AddJsonFilemethods.I'll add the final code here in a day or so once I perfect it.
EDIT:
Note that the code above is actually for a YAML configuration file. You will need to tweak the single line that load the YAML to use JSON. I haven't tested these, but they should be close:
JSON:
YAML: