Binding a configuration to an object graph in .NET Core 2.0
You can still do both of these. Since you are in a console application, and as such likely not using the ASP.NET Core metapackage, you need to make sure to have the correct dependencies.
In order to bind the configuration to an object, you need the Microsoft.Extensions.Configuration.Binder
package. Then, both solutions should work just fine.
Btw. even if you are in a console application, you could still make use of the dependency injection container that comes with ASP.NET Core. I’ve personally found it very simple to set up, so if you can still modify your application to use it, it might be worth it. The setup would just look like this:
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json", optional: false)
.Build();
var services = new ServiceCollection();
services.AddOptions();
// add your services here
services.AddTransient<MyService>();
services.AddTransient<Program>();
// configure options
services.Configure<AppSettings>(configuration.GetSection("App"));
// build service provider
var serviceProvider = services.BuildServiceProvider();
// retrieve main application instance and run the program
var program = serviceProvider.GetService<Program>();
program.Run();
Then, all your registered services can take dependencies just like they would do in ASP.NET Core. And to consume your configuration, you could then inject the IOptions<AppSettings>
type like usually.
I was still having issues with this until I finally figured it out today.
The code was running without issues, but all the properties were still null, even after binding. I was doing this:
public class AppSettings
{
public string MyProperty
}
and it turns out you have to do this:
public class AppSettings
{
public string MyProperty { get; set; }
}
It only works if your class has Properties, not Fields. This wasn't clear to me.
If you want to register the config during Startup
add this to Startup.cs
:
services.Configure<AppSettings>(Configuration.GetSection("App"));
which you can then access by injecting an instance of IOptions<>
:
private readonly AppSettings _appSettings;
public MyClass(IOptions<AppSettings> appSettings) {
_appSettings = appSettings.Value;
}