damirarh / damirscorner-utterances

utteranc.es comments for https://damirscorner.com
0 stars 0 forks source link

/blog/posts/20210305-ConfiguringEnvironmentsInNetConsoleApp.html #117

Open damirarh opened 1 year ago

damirarh commented 1 year ago

Imported

URL: https://www.damirscorner.com/blog/posts/20210305-ConfiguringEnvironmentsInNetConsoleApp.html

damirarh commented 1 year ago

Imported comment written by Paul Roskilly on 2021-05-26T10:36:40

What if you want a mixture of Staging and Production console apps deployed to the same server. The environment variable wouldn't be specific to any one app, its a server wide setting.

damirarh commented 1 year ago

Imported comment written by Nathan Risto on 2022-08-24T16:20:14

Yes, we run into that all the time and Microsoft still won't provide a useful solution to that problem. We're forced to pass in the environment variable in the command-line and write all the parse logic to read the correct appsettings.json ourselves, skipping all their default builders. We've contacted Microsoft to explain this issue, but they just kind of stare back confused wondering why everyone isn't on azure running dedicated app servers for every environment. They don't care.

damirarh commented 1 year ago

Imported comment written by Tim Wilson on 2022-10-06T16:59:19

Have you tried just passing a command-line argument with the environment name? In the code in this article you have full control of how you build the appsettings file path. You do not have to use the environment variable.

I am solving this same problem as shown below. You just need to implement "GetEnvironment()" to find the environment based on args passed in and provide a default if the argument is not found.

public static (IConfigurationRoot Configuration, string EnvironmentName) Build(string[] args)
{
var environment = GetEnvironment(args);
var configuration = BuildConfiguration(environment);

return (configuration, environment);
}

private static IConfigurationRoot BuildConfiguration(string environment)
{
try
{
return new Microsoft.Extensions.Configuration.ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"appsettings.{environment}.json")
.Build();
}
catch (FileNotFoundException)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"No configuration file was found for environment {environment}");
Console.ForegroundColor = ConsoleColor.Black;

throw;
}
}