.Net Core Web.config Migration
Thank you .Net Core for finally moving from XML to JSON. As a json lover the xml within .Net always bothered me. But the config is now stored in json, which makes it easier to maintain, and you need to map it to an actual class, which enables you to make use of the typing in C#. Now you are able to take advantage of intellisense even with the web.config, which is now called appsettings in .Net Core.
Now the appSettings look like
Create a cs class that correspond to the appsettings variables that you want to use in your application.
And now in your ConfigureServices method in the startup.cs, register this class and inject it into your application through .Net Core’s DI.
services.Configure<ConfigOptions>(Configuration.GetSection(ConfigOptions.Position))
.AddSingleton(sp => sp.GetRequiredService<IOptions<ConfigOptions>>().Value);
Now you are able to use ConfigOptions class as a singleton throughout your application.
private ConfigOptions ConfigOptions { get; set; }public AuthenticationService(ConfigOptions configOptions)
{
ConfigOptions = configOptions;
}
If you need to use the AppSettings variables at a place where ConfigOptions is not yet available, you can also retrieve the values through the built in IConfiguration interface, for example at the startup.cs
public IConfiguration Configuration { get; }public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
and then
var configOptions = Configuration.GetSection(ConfigOptions.Position).Get<ConfigOptions>();
and you should be able to access all the values in the configOptions.
If you encountered this error “‘IConfiguration’ does not contain a definition for ‘Get’”, refer to this stackoverflow post
This article is a part of the .Net to .Net Core Migration Series
https://theochiu2010.medium.com/net-to-net-core-migration-2eb31584f95c