想象一下,你寫一個控制檯應用程序,你想要從配置文件中以強類型方式讀取配置。json
.NET Core 能夠幫助咱們解決。 一般我會在ASP.NET Core MVC中演示,但簡單起見,只在控制檯應用程序中演示。app
讓咱們建立兩個配置類,用於保存應用程序和模塊名稱。ui
public class MySettings { public string ApplicationName { get; set; } } public class MyModuleSettings { public string ModuleName { get; set; } }
應用程序配置文件以下所示:spa
{ "ApplicationName": "My sample application", "SectionA": { "ModuleName": "My sample module" } }
最後,讓咱們在應用程序中使用它。code
public class Program { public static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); IConfigurationRoot configuration = builder.Build(); var settings = new MySettings(); configuration.Bind(settings); var moduleSettings = new MyModuleSettings(); configuration.GetSection("SectionA").Bind(moduleSettings); Console.WriteLine($"My application name is '{settings.ApplicationName}'"); Console.WriteLine($"My module name is '{moduleSettings.ModuleName}'"); Console.ReadLine(); } }
全部的實現都是經過「Bind」方法。orm
不要忘記添加所需的依賴關係。 project.json應該包含如下內容:blog
{ "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" } } }
運行結果:ci
在.NET Core應用程序中使用強類型配置類很是容易!但願本文對你有所幫助~。get