Author : MD TAREQ HASSAN | Updated : 2020/12/11
Pre-requisites
Dependency injection in console app
Nuget Packages
Install-Package Microsoft.Extensions.Configuration.Json
appsettings json
- Right click on project > Add > New Item
- Search json > JSON file >
appsettings.json
> Add - Right click on (newly created)
appsettings.json
> properties - Copy to output directory > Copy if newer
appsettings.json
{
"test-key": "This is value for test key"
}
Configuration Without DI
Program.cs
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using static System.Diagnostics.Debug;
namespace ConsoleApp.AppSettings
{
class Program
{
private static IConfiguration _configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.Build();
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
// ... ... ...
WriteLine("\n\n\n\n\n");
WriteLine("=====================================================================================\n\n");
WriteLine("AppSettings without DI is working...\n");
var testKey = "test-key";
var testValue = _configuration[testKey];
WriteLine($"Test Value from appsettings.json: {testValue}");
WriteLine("\n\n=================================================================================");
WriteLine("\n\n\n\n\n");
Console.Read();
}
}
}