[英]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 namedCreateWebHostBuilder
, which separates it from the code inMain
that callsRun
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 aCreateWebHostBuilder
method that they can call at design time to configure the host without running the app.这些工具希望找到一个CreateWebHostBuilder
方法,他们可以在设计时调用该方法来配置主机,而无需运行应用程序。 An alternative is to implementIDesignTimeDbContextFactory
.另一种方法是实现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.