skip to Main Content

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.

enter image description here

enter image description here

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


  1. Chosen as BEST ANSWER

    I already got it. I Added Environment=DOTNET_ENVIRONMENT=Development on .Service file.


  2. You will need to access HostBuilderContext in Main() to access Hosting Environment something like this

     CreateHostBuilder(args)
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
                    if (env.IsDevelopment() || env.EnvironmentName.ToLower() == "dev")
                        config.AddJsonFile("appsettings.dev.json", optional: true, reloadOnChange: true);
                    else if (env.IsStaging() || env.EnvironmentName.ToLower() == "stage")
                        config.AddJsonFile("appsettings.stage.json", optional: true, reloadOnChange: true);                    
    
                    config.AddEnvironmentVariables();
                }).Build().Run();
    

    Also, don’t forget to add environmentVariables

    • in launchSettings.json of Project Properties
    • On linux, using command setx ASPNETCORE_ENVIRONMENT "Development" and check environment setting if it’s correct using echo ASPNETCORE_ENVIRONMENT
    {
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:57993/",
          "sslPort": 0
        }
      },
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        }
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search