Imagine that you write a console application and you want to read the configuration in a strongly typed manner from the configuration file.
. NET Core can help us solve. I will usually demonstrate in ASP. NET Core MVC, but for simplicity, only in console applications.
Let's create two configuration classes to hold the application and module names.
Public class mysettings{ publicstringgetset;} Public class mymodulesettings{ publicstringgetset;}
The application configuration file looks like this:
{ "ApplicationName""My sample application" , " Sectiona " : { "modulename" "My Sample module" }}
Finally, let's use it in the application.
Public classprogram{ Public Static voidMain (string[] args) { varBuilder =NewConfigurationbuilder (). Setbasepath (Directory.GetCurrentDirectory ()). Addjsonfile ("Appsettings.json", Optional:false, Reloadonchange:true) . Addenvironmentvariables (); Iconfigurationroot Configuration=Builder. Build (); varSettings =Newmysettings (); Configuration. Bind (settings); varModulesettings =Newmymodulesettings (); Configuration. GetSection ("Sectiona"). Bind (modulesettings); Console.WriteLine ($"My application name is ' {settings. ApplicationName} '"); Console.WriteLine ($"My Module name is ' {modulesettings.modulename} '"); Console.ReadLine (); }}
All implementations are through the "Bind" method.
Don't forget to add the required dependencies. Project.json should contain the following content:
{ "version":"1.0.0-*", "buildoptions": { "Emitentrypoint":true }, "Dependencies": { "Microsoft.Extensions.Configuration":"1.1.0", "Microsoft.Extensions.Configuration.Binder":"1.1.0", "Microsoft.Extensions.Configuration.EnvironmentVariables":"1.1.0", "Microsoft.Extensions.Configuration.FileExtensions":"1.1.0", "Microsoft.Extensions.Configuration.Json":"1.1.0", "Microsoft.NETCore.App": { "type":"Platform", "version":"1.0.1" } }, "Frameworks": { "netcoreapp1.0": { "Imports":"Dnxcore50" } }}
Operation Result:
Using a strongly typed configuration class in a. NET core application is easy! Hope this article is helpful to you ~.
Using strongly-typed configurations in. NET Core Console applications