IHostBuilder configures an application host before it is built. The resulting IHost contains the server, services, configuration, and hosting infrastructure, then runs through the application's entry point. section 30.2
A typical generic-host startup flow is:
- Call Host.CreateDefaultBuilder(args) to create an IHostBuilder with default configuration, logging, environment, and dependency-injection settings. section 30.7
- Customize the builder with ConfigureWebHostDefaults, then select Startup through UseStartup<Startup>() for web applications. section 30.2
- Call Build() to create the IHost, then Run() to start listening for requests or executing hosted services. section 30.2
- Place service registration and middleware configuration in Startup for web apps, or ConfigureServices directly on the builder for worker services. section 30.7 section 34.2.1
A conventional ASP.NET Core entry point
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); Main calls CreateHostBuilder(args).Build().Run(). section 30.2
Listing 30.1 The Program.cs file configures and runs an IHost
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args) #1
.Build() #2
.Run(); #3
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args) #4
.ConfigureWebHostDefaults(webBuilder => #5
{
webBuilder.UseStartup<Startup>(); #6
});
}
Browse the complete Program.cs listing showing default-host creation, web-host customization, Startup selection, Build, and Run. section 30.2
