简体   繁体   中英

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();
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM