13

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".

James Graham
  • 39,063
  • 41
  • 167
  • 242
Dimitar Dimitrov
  • 14,311
  • 7
  • 45
  • 76
  • [CreateDefaultBuilder](https://github.com/dotnet/aspnetcore/blob/1480b998660d2f77d0605376eefab6a83474ce07/src/DefaultBuilder/src/WebHost.cs#L155) is wrapper method which initializes features like --- use Kestrel as the web server and configure it using the application's configuration providers,. If you see the implementation, it injects the hosting environment. If you want to have something similar then you refer the mentioned [code](https://github.com/dotnet/aspnetcore/blob/1480b998660d2f77d0605376eefab6a83474ce07/src/DefaultBuilder/src/WebHost.cs#L155). – user1672994 Sep 28 '20 at 12:52

1 Answers1

2

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>();
                });
Zinov
  • 3,350
  • 5
  • 31
  • 61