Home > Net >  Environment specific config not loaded when passed as an argument - "Unhandled exception Failed
Environment specific config not loaded when passed as an argument - "Unhandled exception Failed

Time:04-22

I am trying to deploy a dotnet core 3.0 windows service on a new Windows server. I have a ps1 script that creates the service like so:

$name = "DataTransformService"
$params = @{
  Name           = $name
  BinaryPathName = '"C:\services\transformService\DataTransform.Service.exe Test"'
  DisplayName    = $name
  StartupType    = "Automatic"
}
New-Service @params

However, when I try to start the service using the Services application on Windows and start it I get this error: enter image description here

When I tried to manually invoke the service using the binary:

C:\services\transformService\DataTransform.Service.exe Test

I get this error:

PS C:\services\transformService> C:\services\transformService\DataTransform.Service.exe Test
Configured for environment Test_ENVIRONMENT
Unhandled exception. System.MissingFieldException: Failed to map app settings section 'ConnectionStrings' as it wasn't found in appsettings.json or appsettings.Production.json. Add this section or remove class 'ConnectionStringsSettings' from the 'Core.Settings' namespace.
   at DataTransform.Service.StartupConfiguration.ConfigureSettingsExtensions.ConfigureSettingSection[T](IServiceCollection services, IConfiguration configuration, IHostEnvironment hostingEnvironment) in D:\_Code\DataTransform.Service\DataTransform.Service\StartupConfiguration\ConfigureSettingsExtensions.cs:line 48
   at DataTransform.Service.StartupConfiguration.ConfigureSettingsExtensions.ConfigureSettings(IServiceCollection services, IConfiguration configuration, IHostEnvironment hostingEnvironment) in D:\_Code\DataTransform.Service\DataTransform.Service\StartupConfiguration\ConfigureSettingsExtensions.cs:line 26
   at DataTransform.Service.Program.<>c.<CreateHostBuilder>b__1_2(HostBuilderContext hostContext, IServiceCollection services) in D:\_Code\DataTransform.Service\DataTransform.Service\Program.cs:line 47
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at DataTransform.Service.Program.Main(String[] args) in D:\_Code\DataTransform.Service\DataTransform.Service\Program.cs:line 15

I have a few environments defined such as below:

enter image description here

This is my Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args)
            .Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .UseWindowsService()
            .ConfigureHostConfiguration((configBuilder) =>
            {
                if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && !string.IsNullOrWhiteSpace(args[0]))
                {
                    Console.WriteLine($"Configured for environment {args[0]}_ENVIRONMENT");
                    configBuilder.AddEnvironmentVariables($"{args[0]}_");
                }
                else
                {
                    var environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
                    Console.WriteLine($"Configured for environment {environmentName}");
                    configBuilder.AddEnvironmentVariables();
                }
            })
            .ConfigureLogging(...)
            .ConfigureServices(...);
}


this is my appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "EventLog": {
      "LogLevel": {
        "Default": "Information",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    }
  },
  "Worker": {
    "TargetDatabaseName": "TransformedData",
    ...
  }
}

this is appsettings.Test.json

{
  "ConnectionStrings": {
    <connection strings here>
  },
  "Environment": {
    "Name": "Test"
  },
  "Worker": {
    ...
  }
}

What am I missing here? I would appreciate some help, please.

CodePudding user response:

I had exactly the same problem a few days ago, it was so weird. the problem is when execute your app by Cmd or Powershell and assume they run at path C:\Users\YourName it tries to find appsettings.json in this path C:\Users\YourName\appsettings.json!! (if you copy/past your appsettings.json in that path your app will run).

So for solve this issue you need to specify base path like this:

 .ConfigureHostConfiguration((configBuilder) =>
            {
              configBuilder.Sources.Clear();
              configBuilder.SetBasePath(
 
               Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
               .AddJsonFile("./appsettings.json", true, true)
               .AddJsonFile($"./appsettings.{args[0]}.json", true, true);


                if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && !string.IsNullOrWhiteSpace(args[0]))
                {
                    Console.WriteLine($"Configured for environment {args[0]}_ENVIRONMENT");
                    configBuilder.AddEnvironmentVariables($"{args[0]}_");
                }
                else
                {
                    var environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
                    Console.WriteLine($"Configured for environment {environmentName}");
                    configBuilder.AddEnvironmentVariables();
                }
            })
  • Related