Created
May 1, 2021 19:55
-
-
Save manoj-choudhari-git/64b5c68ac86d8faafa78c0087fa52330 to your computer and use it in GitHub Desktop.
C# .NET - How to use appsettings.json with console application
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
// Program.cs | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Setup Host | |
var host = CreateDefaultBuilder().Build(); | |
// Invoke Worker | |
using IServiceScope serviceScope = host.Services.CreateScope(); | |
IServiceProvider provider = serviceScope.ServiceProvider; | |
var workerInstance = provider.GetRequiredService<Worker>(); | |
workerInstance.DoWork(); | |
host.Run(); | |
} | |
static IHostBuilder CreateDefaultBuilder() | |
{ | |
return Host.CreateDefaultBuilder() | |
.ConfigureAppConfiguration(app => | |
{ | |
app.AddJsonFile("appsettings.json"); | |
}) | |
.ConfigureServices(services => | |
{ | |
services.AddSingleton<Worker>(); | |
}); | |
} | |
} | |
// Worker.cs | |
internal class Worker | |
{ | |
private readonly IConfiguration configuration; | |
public Worker(IConfiguration configuration) | |
{ | |
this.configuration = configuration; | |
} | |
public void DoWork() | |
{ | |
var keyValuePairs = configuration.AsEnumerable().ToList(); | |
Console.ForegroundColor = ConsoleColor.Green; | |
Console.WriteLine("=============================================="); | |
Console.WriteLine("Configurations..."); | |
Console.WriteLine("=============================================="); | |
foreach (var pair in keyValuePairs) | |
{ | |
Console.WriteLine($"{pair.Key} - {pair.Value}"); | |
} | |
Console.WriteLine("=============================================="); | |
Console.ResetColor(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment