I have a .net core 3.1 background worker that is installed in ubuntu as a background worker. But It can’t get the value of the environment variables which I need for multi-configurations that’s why as you can see the value of host environment is the default which is Production.
I already tried getting it thru hostenvironment.environmentname and thru Environment.GetEnvironmentVariable.
My Service file in /etc/systemd/
[Unit]
Description=TestService
[Service]
Type=notify
WorkingDirectory=/home/centos/TestService/
ExecStart=/usr/bin/dotnet /home/centos/TestService/WorkerService2.dll
User=centos
[Install]
WantedBy=multi-user.target
Code in NET Core 3.1 background worker.
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
_logger.LogError("ERROR testing");
_logger.LogInformation($"Hosting Enviornment: {_hostEnvironment.EnvironmentName}");
_logger.LogInformation(_configuration["Test"]);
var basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var contentroothpath = _hostEnvironment.ContentRootPath;
Console.WriteLine($"basepath = {basePath}");
Console.WriteLine($"contentrootpath = {contentroothpath}");
_logger.LogInformation($"basepath = {basePath}");
_logger.LogInformation($"contentrootpath = {contentroothpath}");
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var environmentName2 = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
_logger.LogInformation($"ASPNETCORE_ENVIRONMENT = {environmentName}");
_logger.LogInformation($"DOTNET_ENVIRONMENT = {environmentName2}");
Output on cmd.
Code in program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSystemd()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
var basePath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
//NLog.LogManager.LoadConfiguration($"{basePath}/NLog.{hostContext.HostingEnvironment.ContentRootPath}.config");
})
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile(
$"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
//NLog.LogManager.LoadConfiguration($"/home/centos/TestService/{hostingContext.HostingEnvironment.EnvironmentName}.config");
//NLog.LogManager.LoadConfiguration($"{basePath}" +
// $"/NLog.{hostingContext.HostingEnvironment.EnvironmentName}.config");
});
2
Answers
I already got it. I Added Environment=DOTNET_ENVIRONMENT=Development on .Service file.
You will need to access HostBuilderContext in Main() to access Hosting Environment something like this
Also, don’t forget to add environmentVariables
setx ASPNETCORE_ENVIRONMENT "Development"
and check environment setting if it’s correct usingecho ASPNETCORE_ENVIRONMENT