NorthwindTraders icon indicating copy to clipboard operation
NorthwindTraders copied to clipboard

[Discussion] Move IWebHostBuilder to IHostBuilder in Program.cs

Open JoeyMckenzie opened this issue 5 years ago • 0 comments

Noticed that in the migration to .NET Core 3.0, Program.cs was still utilizing the IWebHostBuilder to configure and bootstrap the host. In reference to IHostBuilder, the team states:

In versions of ASP.NET Core earlier than 3.0, the Web Host is used for HTTP workloads. The Web Host is no longer recommended for web apps and remains available only for backward compatibility.

In project templates for ASP.NET Core projects targeting netcoreapp3.0 and up, they've changed to using the IHostBuilder from IWebHostBuilder, and I believe this update should be made to the WebUI project. Utilizing CreateDefaultBuilder(string[] args) from the Host class, the current host builder method can be simplified to just building with the default methods.

The current implmentation:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(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)
                        .AddJsonFile($"appsettings.Local.json", optional: true, reloadOnChange: true);

                    if (env.IsDevelopment())
                    {
                        var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                        if (appAssembly != null)
                        {
                            config.AddUserSecrets(appAssembly, optional: true);
                        }
                    }

                    config.AddEnvironmentVariables();

                    if (args != null)
                    {
                        config.AddCommandLine(args);
                    }
                })
                .UseStartup<Startup>();

utilizes some of the same code that is shipped with the Host::CreateDefaultBuilder(string[] args) method, particularly on lines 70-92 where you are setting up the app config files, user secrets, and environment variables. Moving to the Host implementation, I believe this can be simplified to:

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

Not a huge issue as both implementations are supported, just some food for thought.

JoeyMckenzie avatar Jan 30 '20 17:01 JoeyMckenzie