Why is function CreateWebHostBuilder() created?

asp.net-core asp.net-core-2.2 c# entity-framework-core visual-studio

Question

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();
        }
    }
}
1
1
10/18/2019 8:10:07 AM

Accepted Answer

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.

5
10/17/2019 3:31:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow