简体   繁体   English

为什么要创建 function CreateWebHostBuilder()?

[英]Why is function CreateWebHostBuilder() created?

When creating a ASP.NET Core 2.2 Web API, Visual Studio 2019 creates this code:创建 ASP.NET Core 2.2 Web API 时,Visual Studio 2019 会创建以下代码:

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 ?为什么要创建 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 : Entity Framework Core 工具使用CreateWebHostBuilder方法如下所述:

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.调用CreateDefaultBuilder的代码位于名为CreateWebHostBuilder的方法中,该方法将其与Main中调用构建器 object 上的Run的代码分开。 This separation is required if you use Entity Framework Core tools .如果您使用Entity Framework Core 工具,则需要这种分离。 The tools expect to find a CreateWebHostBuilder method that they can call at design time to configure the host without running the app.这些工具希望找到一个CreateWebHostBuilder方法,他们可以在设计时调用该方法来配置主机,而无需运行应用程序。 An alternative is to implement IDesignTimeDbContextFactory .另一种方法是实现IDesignTimeDbContextFactory For more information, see Design-time DbContext Creation .有关详细信息,请参阅设计时 DbContext 创建

If you're not using EF Core, you can collapse it into the Main method, as you've suggested.如果您不使用 EF Core,则可以按照您的建议将其折叠到Main方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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