Search code examples
c#visual-studioasp.net-coreentity-framework-coreasp.net-core-2.2

Why is function CreateWebHostBuilder() created?


When creating a ASP.NET Core 2.2 Web API, Visual Studio 2019 creates this code:

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

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

Why the heck is it creating a function CreateWebHostBuilder ? Why does it not just create a code as follows?

namespace myapi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build().Run();
        }
    }
}

Solution

  • The CreateWebHostBuilder method is used by the Entity Framework Core tools, as described here:

    The code that calls CreateDefaultBuilder is in a method named CreateWebHostBuilder, which separates it from the code in Main that calls Run on the builder object. This separation is required if you use Entity Framework Core tools. The tools expect to find a CreateWebHostBuilder method that they can call at design time to configure the host without running the app. An alternative is to implement IDesignTimeDbContextFactory. For more information, see Design-time DbContext Creation.

    If you're not using EF Core, you can collapse it into the Main method, as you've suggested.