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

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();
        }
    }
}

Configuration With DI