Host.CreateDefaultBuilder(args) creates an IHostBuilder with useful defaults, so you can start an application without assembling its hosting setup from scratch. Configure the builder, call Build() to create an IHost, then call Run() to start it. section 30.4 section 30.2
The defaults handle several setup tasks:
- Set the content root to the current directory, where the application can find configuration or Razor files. section 30.4
- Read hosting settings from DOTNET_-prefixed environment variables and command-line arguments, including information used to determine the hosting environment. section 30.4
- Supply default application configuration and logging providers and configure dependency-injection settings. section 30.7
For an ASP.NET Core app using Startup, follow CreateDefaultBuilder(args) with ConfigureWebHostDefaults(...), and select Startup with UseStartup<Startup>(). Startup then registers services and defines the middleware pipeline and endpoints. CreateHostBuilder is commonly the name of your own method wrapping this setup; it is not another name for Host.CreateDefaultBuilder(). section 30.2 section 30.7
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
});
}
Follow the calls from CreateDefaultBuilder(args) through web-host configuration, Build(), and Run(). section 30.2
You can adjust the returned builder rather than replace every default. For example, add a Seq logging provider with ConfigureLogging(), or use ConfigureAppConfiguration() to change configuration sources. Clearing the source collection replaces the providers added by default, so do that only when you intend to supply replacements. Creating a HostBuilder directly is an option when you want to set everything up yourself. section 30.4
A host without a web app
A worker service can call Host.CreateDefaultBuilder(args), register a BackgroundService with ConfigureServices(), then Build() and Run() the host. The same starting point is useful even when the application does not handle HTTP requests. section 34.2.1
