Home > Mobile >  ASPNETCORE_ENVIRONMENT equivalent for .NET Core WPF app?
ASPNETCORE_ENVIRONMENT equivalent for .NET Core WPF app?

Time:01-25

I'm developing a .NET Core (.NET 6) WPF app, and I have a problem detecting the dev environment (Development or Production).

I'm creating a IHost when my WPF app starts, in order to use Dependency Injection and all the other .NET Core goodies, like this:

public partial class App : Application
{
    private readonly IHost host;

    public App()
    {
        host = Host.CreateDefaultBuilder()
            .UseContentRoot(CoreConstants.MaintenanceToolBinFolder)
            .ConfigureServices((context, services) =>
            {
                var configuration = context.Configuration;
                //...
            })
            .Build();
    }
}

Now, in an ASP.net Core web app this would automatically read the ASPNETCORE_ENVIRONMENT environmental variable and use it to determine the current environment. However, this is completely ignored here, and the environment is always "Production".

What is the proper way to detect the environment in this case? Should I just manually read the variable and set the environment, or is there a more "proper" way?

CodePudding user response:

Since you are using generic host (Host.CreateDefaultBuilder()) you should be able to use DOTNET_ENVIRONMENT variable. From docs:

  • Loads host configuration from:
    • Environment variables prefixed with DOTNET_.

CodePudding user response:

I just did my very first "ASP-like" WPF app and it works like a charm.

Here is my code, with Dependency Injection and Serilog logger configuration as bonus:

public partial class App : Application
{
    private IHost? _host;

    protected override void OnStartup(StartupEventArgs e)
    {
        Startup? startup = null;
        this._host = Host.CreateDefaultBuilder(e.Args)
            .ConfigureHostConfiguration(config =>
            {
                config.AddEnvironmentVariables(prefix: "APP_");
            })
            .ConfigureAppConfiguration((hostingContext, configBuilder) =>
            {
                configBuilder.Sources.Clear();

                IHostEnvironment env = hostingContext.HostingEnvironment;

                configBuilder
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: false)
                    ;

                if (env.IsDevelopment())
                {
                    configBuilder.AddUserSecrets(Assembly.GetExecutingAssembly());
                }

                IConfiguration configuration = configBuilder.Build();

                Log.Logger = new LoggerConfiguration()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                    .Enrich.FromLogContext()
                    .ReadFrom.Configuration(configuration)
                    .CreateLogger();

                Log.Information("*** Starting application ***");
            })
            .ConfigureServices((_, services) =>
            {
                services.AddSingleton< ... >();
                    ...
            })
            .UseSerilog()
            .Build()
            ;

        IServiceProvider sp = this._host.Services;

        var window = sp.GetRequiredService<MainWindow>();
        window.Show();
    }

    protected override void OnExit(ExitEventArgs e)
    {
        base.OnExit(e);
        this._host?.Dispose();
    }
}

Also remember to configure the launch settings in the Project Property window or directly in the launchSettings.json file:

{
  "profiles": {
    "<app name>": {
      "commandName": "Project",
      "environmentVariables": {
        "APP_ENVIRONMENT": "Development"
      }
    }
  }
}

Note: I'm using .NET 7.

  • Related