Use IWebHostEnvironment in Program.cs web host builder in ASP.NET Core 3.1

Viewed 2605

I have an ASP.NET Core 3.1 application, and I need to access the IWebHostEnvironment in the Program.cs web host builder. This is what I have right now (Program.cs):

public class Program {

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

    private static bool IsDevelopment => 
        Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";

    public static string HostPort => 
        IsDevelopment 
            ? "5000" 
            : Environment.GetEnvironmentVariable("PORT");

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls($"http://+:{HostPort}")
            .UseSerilog((context, config) => {
                config.ReadFrom.Configuration(context.Configuration);
            })
            .UseStartup<Startup>();
}

Instead of doing the IsDevelopment check the way I do it, I would like to use the IsDevelopment() method from IWebHostEnvironment, not entirely sure how to do that. What I have right now works, but honestly it doesn't "feel right".

1 Answers

If you want to use the IWebHostingEnvironment you should get it from the context parameter of ConfigureAppConfiguration

 public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((context, builder) =>
                {
                    var isDev = context.HostingEnvironment.IsDevelopment();
                    var isProd = context.HostingEnvironment.IsProduction();
                    var envName = context.HostingEnvironment.EnvironmentName;
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
Related