liveBook · Manning

HostBuilder

As explained in ASP.NET Core in Action, 3e

HostBuilder is a .NET hosting API type that configures application services, hosting, configuration, and middleware before creating an application host.

HostBuilder configures an application’s hosting environment, configuration, logging, dependency injection, web server, and middleware before Build() creates an IHost. Run the resulting host with Run(). section 30.4 section 30.7

Customize the default host

A practical starting point is Host.CreateDefaultBuilder(args), which supplies conventional defaults. Customize only what the application needs: CreateHostBuilder(args).Build().Run(); and chain ConfigureLogging, ConfigureAppConfiguration, or ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()). section 30.4

The default builder establishes several hosting behaviors:

  • Sets the content root to the application’s current directory; this is separate from the web root used for browser-accessible static files. section 30.4
  • Reads hosting configuration from DOTNET_ environment variables and command-line arguments, then supplies default logging, configuration providers, and dependency-injection settings. section 30.4 section 30.7
  • Connects web hosting to Startup, whose methods register services, configure middleware, and register endpoints. section 30.7
Listing 30.5 The Host.CreateDefaultBuilder method
public static IHostBuilder CreateDefaultBuilder(string[] args)
{
  var builder = new HostBuilder()                                    #1
    .UseContentRoot(Directory.GetCurrentDirectory())                 #2
    .ConfigureHostConfiguration(IConfigurationBuilder config =>      #3
    {                                                                #3
        config.AddEnvironmentVariables("DOTNET_");                   #3
        config.AddCommandLine(args);                                 #3
    })                                                               #3
    .ConfigureAppConfiguration((hostingContext, config) =>           #4
    {                                                                #4
        IHostEnvironment env = hostingContext.HostingEnvironment;    #4
        config                                                       #4
            .AddJsonFile("appsettings.json")                         #4
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json"); #4
 
        if (env.IsDevelopment())                                     #4
        {                                                            #4
            config.AddUserSecrets();                                 #4
        }                                                            #4
 
            config                                                   #4
                .AddEnvironmentVariables()                           #4
                .AddCommandLine();                                   #4
    })                                                               #4
    .ConfigureLogging((hostingContext, logging) =>                   #5
    {                                                                #5
        logging.AddConfiguration(                                    #5
          hostingContext.Configuration.GetSection("Logging"));       #5
        logging.AddConsole();                                        #5
        logging.AddDebug();                                          #5
        logging.AddEventSourceLogger();                              #5
        logging.AddEventLog();                                       #5
    })                                                               #5
    .UseDefaultServiceProvider((context, options) =>                 #6
    {                                                                #6
        var isDevelopment = context.HostingEnvironment               #6
                                   .IsDevelopment();                 #6
        options.ValidateScopes = isDevelopment;                      #6
        options.ValidateOnBuild = isDevelopment;                     #6
    });                                                              #6
 
  return builder;                                                    #7
}
#1 Creates an instance of HostBuilder
#2 The content root defines the directory where configuration files can be found.
#3 Configures hosting settings such as determining the hosting environment
#4 Configures application settings
#5 Sets up the logging infrastructure
#6 Configures the DI container, optionally enabling verification settings
#7 Returns HostBuilder for further configuration by calling extra methods before calling Build()

Inspect the default builder’s construction sequence, including content-root setup, host configuration, application configuration, and other framework defaults. section 30.4

Listing 36.7 Creating an integration test with TestServer
public class StatusMiddlewareTests
{
    [Fact]
    public async Task StatusMiddlewareReturnsPong()
    {
        var hostBuilder = new HostBuilder()                        #1
            .ConfigureWebHost(webHost =>                           #1
            {
                webHost.Configure(app =>                           #2
                    app.UseMiddleware<StatusMiddleware>());        #2
                webHost.UseTestServer();                           #3
            });
 
        IHost host = await hostBuilder.StartAsync();               #4
        HttpClient client = host.GetTestClient();                  #5
 
        var response = await client.GetAsync("/ping");             #6
 
        response.EnsureSuccessStatusCode();                        #7
        var content = await response.Content.ReadAsStringAsync();  #8
        Assert.Equal("pong", content);                             #8
    }
}

See HostBuilder used with TestServer to build an in-memory application and obtain an HttpClient for integration requests without opening a network port. section 36.3.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains default setup, customization points, and Build()/Run() lifecycle, while deferring implementation details behind framework helpers.
Examples
Uses default-builder customization, Startup wiring, and an in-memory TestServer integration test with HttpClient.
What it assumes
Assumes basic C# application structure and introduces hosting, Startup configuration, dependency injection, middleware, and application lifecycle roles.
What you can do after
Build it from scratch or customize defaults, then run an application host or exercise a web pipeline in memory.
How it connects
Connects IHostBuilder with Startup, dependency injection, middleware, configuration, logging, WebApplicationBuilder, Kestrel, and TestServer.

Also explained in

Compare how 2 books explain HostBuilder →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.