I am trying to figure if there is way to add appsettings.json
support to WindowsForms application, including adding environment related appsettings.{env.EnvironmentName}.json
files on top, similar to what .NET Worker Service does in console application.
Main target is that I enable reading of DOTNET_ENVIRONMENT
environment variable from multiple sources, without re-implementing it line by line.
.NET 6/7 Windows Forms project using Main(...)
method to instantiate the application and manage it's lifetime and not IHostEnvironment
like WorkerService
or web app:
namespace WinFormsApp1;
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
I've been able to add static appsettings.json
support, without environments simply by using ConfigurationBuilder
(independent from HostEnvornment
).
[STAThread]
static void Main()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var configuration = builder.Build();
var myConnection = configuration.GetConnectionString("MyDB");
// ...
}
The problem is to add DOTNET_ENVIRONMENT
variable that can be read from multiple sources, similar to what a Worker Service does in Console app.
HostBuilder solutions
Majority "solution" I've found rely on Host.CreateDefaultBuilder(...)
method and subsequent IHost.Run()
to start the app, which cannot be used to start WinForms app.
.AddEnvironmentVariables()
solutions
Also, there is a category of solutions proposing to use .AddEnvironmentVariables()
method from Microsoft.Extensions.Configuration.EnvironmentVariables
NuGet package, but that achieves completely different results (extends the Configuration
object to read currently set environment variables, but does not extend appsettings.json
).
Is there any way to configure and initialize IHostEnvironment
object without actually using IHost
to run the application?
UPDATE: The linked answer provided in "duplicate question" link does too many things that are not necessary and create performance overhead for my use-case. There is better answer for this question.