.Net5: How do I get the EnvironmentName from Program.cs

424 views Asked by At

The following code works perfectly fine in NetCore 3.1 but doesn't work in .Net5

var webHostBuilder = WebHostBuilder(args);
var environment = webHostBuilder.GetSetting("environment");
1

There are 1 answers

0
Edd On BEST ANSWER

Use GetService< IHostEnvironment>

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

namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var hostBuilder = CreateHostBuilder(args).Build();
            var hostEnvironment = hostBuilder.Services.GetService<IHostEnvironment>();

            // Get EnvironmentName
            var environment = hostEnvironment?.EnvironmentName; // Possible values: Development, Production, CustomEnvironment, etc..

            hostBuilder.Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}