Appsettings.Development.json do not seen by console app .net core 3.1 configuration problem
Asked Answered
E

6

9

In my asp.net core 3.1 console app. In main class I have code like this:

class Program
{
    static void Main(string[] args)
    {
        var builder = new ConfigurationBuilder();
        BuildConfig(builder);

        var host = Host.CreateDefaultBuilder()
            .ConfigureServices((context, services) =>
            {
                services.AddTransient<StartService>();
            })
            .Build();
        
        var svc = ActivatorUtilities.CreateInstance<StartService>(host.Services);
        
        svc.Run();
    }

    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true)

            .AddEnvironmentVariables();
    }
}

Environment set to Development enter image description here

and config files like this (only values there differ):

enter image description here

My app keeps taking values from appsettings.json. What to change in order to take values from appsettings.Developement.json?

I also tried like this, but it didn`t work either:

    static void BuildConfig(IConfigurationBuilder builder)
    {
        builder.SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
           .AddJsonFile("appsettings.Development.json", optional: true)

            .AddEnvironmentVariables();
    }

Does anyone can help with that? Files are properly copied to bin enter image description here

Exhume answered 17/12, 2020 at 22:41 Comment(7)
try .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)Uranie
i tried this, but stull the same, gets values from appsettings.jsonExhume
Anyone can help?Exhume
If you want to use appsettings.Development.json rather than appsettings.json,Why not use builder.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables();Pat
@YiyiYou that won`t work either, settings are still taken from appsettings.json even if I do not specifiy path for it.Exhume
Did you ever find a solution to this? I'm facing the exact same problemRattletrap
You don't need the addjsonfile part anymore. The hostbuilder will do this for you. learn.microsoft.com/en-us/aspnet/core/fundamentals/host/…Acceptant
R
5

For .Net 6.0

Add the environment variable DOTNET_ENVIRONMENT=Development

Restart Visual Studio 2022.

Environment Variables

Rawdon answered 15/12, 2021 at 15:13 Comment(1)
You don't need to set this in system properties. You can do this in Visual Studio as a launch profile.Acceptant
K
8

I had the same problem with my console application with default configuration providers. And the reason was the incorrect Environment variable like in your screenshot - ASPNETCORE_ENVIRONMENT. And I fixed it by replacing it by DOTNET_ENVIRONMENT:

enter image description here

Ki answered 28/9, 2021 at 16:28 Comment(1)
I have to say I'm gobsmacked! THIS IS DEAD RIGHT!! I inherited a console app project that never worked right and now I know that one of the reasons was because it had ASPNETCORE_ENVIRONMENT defined instead of DOTNET_ENVIRONMENT. Thanks so much for sharing this.Achates
R
5

For .Net 6.0

Add the environment variable DOTNET_ENVIRONMENT=Development

Restart Visual Studio 2022.

Environment Variables

Rawdon answered 15/12, 2021 at 15:13 Comment(1)
You don't need to set this in system properties. You can do this in Visual Studio as a launch profile.Acceptant
A
4

I just wanted to confirm that the DOTNET_ENVIRONMENT variable worked for me as well, but wanted to add that in Visual Studio 2022 in my .Net 6 Console App I had to configure the value in Launch Profiles, which I navigated to via the Debug Section in Project Properties: enter image description here

I also did NOT need to add the appsettings.Develepment.json file to the builder when I tested this.

All I have in my Program.cs for configuring dependency injection, is this:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

Console.WriteLine("Starting...");

using var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices((_, services) =>
    {
        services.AddTransient<ISqlServerTests, SqlServerTests>();
    })
    .Build();

Console.WriteLine("Done");
Ardussi answered 11/4, 2022 at 12:40 Comment(1)
As a heads up, there can be some strangeness here if trying to run a console app from a ASP .NET core app. With this method the appsettings from the invoking application seem to be used.Patrilineage
A
2

In .NET 5 and higher the setting is called DOTNET_ENVIRONMENT

In your launchprofile.json you should see something like this

  "environmentVariables": {
    "DOTNET_ENVIRONMENT": "Development"
  }

You don't need this piece of code anymore

 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
 .AddJsonFile("appsettings.Development.json", optional: true)

The hostbuilder will do this for you.

Acceptant answered 20/12, 2022 at 13:44 Comment(0)
H
0

I found this on GitHub: https://github.com/aspnet/Hosting/issues/1440.

I think the problem is that the ConfigurationBuilder isn't reading the launchsettings. I added the following to fix that.

static async Task Main(string[] args)
        {
            var builder = new HostBuilder();
            builder
                .ConfigureWebJobs(b =>
                {
                    b.AddAzureStorageCoreServices();
                    //b.AddAzureStorage();
                    b.AddTimers();
                })
                .ConfigureHostConfiguration(configHost =>
                {
                    configHost.AddEnvironmentVariables(prefix: "ASPNETCORE_");
                    configHost.AddCommandLine(args);
                })
                .ConfigureAppConfiguration((hostingContext, config) => 
                {
                    var env = hostingContext.HostingEnvironment;

                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                })
                .ConfigureLogging((context, b) =>
                {
                    b.AddConsole();
                });
            var host = builder.Build();
            using (host)
            {
                // The following code ensures that the WebJob will be running continuously
                await host.RunAsync();
            }
        }
Haemocyte answered 21/12, 2020 at 20:23 Comment(4)
And where exactly does this code go? Can you be more specific?Astral
Now that I look at the original post again, the ConfigurationBuilder is configured but not used. Then the Host is instantiated without the configuration. I think I was having a different problem than the OP.Haemocyte
@SeanHoward thanks for info, but as i said, I tried even hardcode it as .AddJsonFile("appsettings.Development.json", optional: true), and it didnt work either. So I dont think those are envronment variable that are the problem.Exhume
As I said, you have called .AddJsonFile on the builder, but you pass the host to ActivatorUtilities.CreateInstance<StartService>. The builder might as well not be there.Haemocyte
C
0

what worked for me was setting the Copy to Output Directory to Copy if newer

.NET 3.1 - WPF app

enter image description here

Capitulary answered 4/1, 2022 at 2:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.