Created
April 8, 2020 15:18
-
-
Save EyeOfMidas/26d2783a7b3eefb80f9654c1b7ebee5f to your computer and use it in GitHub Desktop.
A simple appsettings.json Configuration loader/viewer for your dotnet core console app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create an appsettings.json in the root directory of your console application | |
// for example, it should look like: | |
// { | |
// "Environment": { | |
// "Token": "abc-123", | |
// "Name": "Production" | |
// } | |
//} | |
// | |
// In your Program.cs file, make sure to add: | |
// using System.Configuration; | |
// | |
// And you can use the configuration in your Main function like this: | |
// | |
// try | |
// { | |
// var config = new ConfigurationLoader(); | |
// config.Load(); | |
// Console.WriteLine(config.GetProperty("Environment.Name")); | |
// } | |
// catch (Exception e) | |
// { | |
// Console.WriteLine(e.Message); | |
// } | |
// | |
// This will output "Production", but otherwise it will output a dynamic object | |
// (typically a JsonElement since we're using the system.text.json library) | |
using System.Text.Json; | |
using System.IO; | |
namespace System.Configuration | |
{ | |
class ConfigurationLoader | |
{ | |
private dynamic configJsonData; | |
public ConfigurationLoader Load(string configFilePath = "appsettings.json") | |
{ | |
var appSettings = File.ReadAllText(configFilePath); | |
this.configJsonData = JsonSerializer.Deserialize(appSettings, typeof(object)); | |
return this; | |
} | |
public dynamic GetProperty(string key) | |
{ | |
var properties = key.Split("."); | |
dynamic property = this.configJsonData; | |
foreach (var prop in properties) | |
{ | |
property = property.GetProperty(prop); | |
} | |
return property; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment