While I was having issues with a publish profiles, I decided to create a small test console app, using .net core 3 and see if my environment variables are getting set and the corresponding appsettings.json file being read from.
So, here goes.
Program.json
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.EnvironmentVariables;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Cmd1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var environmentName =
Environment.GetEnvironmentVariable("ENVIRONMENT");
// create service collection
var services = new ServiceCollection();
// build config
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.AddJsonFile($"appsettings.{environmentName}.json", true)
.AddEnvironmentVariables()
.Build();
// setup config
services.AddOptions();
services.Configure<AppSettings>(configuration.GetSection("App"));
// create service provider
var serviceProvider = services.BuildServiceProvider();
var appSettings = serviceProvider.GetService<IOptions<AppSettings>>();
string env = Environment.GetEnvironmentVariable("Environment");
Console.WriteLine($" We are looking at {appSettings.Value.TempDirectory} from environment: {env}");
}
}
}
Setting Environment for running from Visual Studio
appsettings.json
{
"App": {
"TempDirectory": "d:\temp"
}
}
appsettings.Local.json
{
"App": {
"TempDirectory": "c:\\temp\\rss-hero\\tmp\\"
}
}
appsettings.Test.json
{
"App": {
"TempDirectory": "d:\test"
}
}
Now, going to the commandline and running dotnet run, I get
If I try to set the environment on the commandline, it doesnt seem to take it. What am I missing? Same sort of problem occurs If I use a publish profile for this console app.
[ Edit 2] After adding the ability to use commandline args,
if (args != null)
{
if (args.Length > 0)
{
Environment.SetEnvironmentVariable("Environment", args[1]);
}
}