Generic Host [ Documentation]

The host encapsulates DI, logging, configuration, and IHostedService implementations.

ASP.NET Core creates a WebApplicationBuilder and a WebApplication (a form of the Generic Host) which eliminates the need for a Startup class.

See also: Generic Host

Create a Host with an IHostedService Implementation

CreateDefaultBuilder

await Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<SampleHostedService>();
    })
    .Build()
    .RunAsync();

CreateDefaultBuilder:

  • Sets content root to GetCurrentDirectory
  • Loads host configuration from env vars (prefixed with DOTNET_) then command line args
  • Loads app configuration (appsettings.json —> appsettings.{Environment}.json —> User secrets (in Development environment) —> Env vars —> command line args)
  • Adds logging providers: Console, Debug, EventSource, EventLog (Windows only)
  • If HostingEnvironment == “Development”, enables scope validation and dependency validation

ConfigureWebHostDefaults

For an HTTP workload, call ConfigureWebHostDefaults instead of ConfigureServices:

await Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup<Startup>();
    })
    .Build()
    .RunAsync();

ConfigureWebHostDefaults:

  • Loads host configuration from env vars (prefixed with ASPNETCORE_)
  • Sets Kestrel as the web server and configures it
  • Adds Host Filtering middleware
  • Adds Forwarded Headers middleware if ASPNETCORE_FORWARDEDHEADERS_ENALED == true
  • Enables IIS integration

IHostEnvironment

Inject IHostEnvironment into a class to get information about ApplicationName, EnvironmentName, and ContentRootPath.

Web apps implement IWebHostEnvironment which inherits IHostEnvironment and adds the WebRootPath.

Host Configuration

Host configuration is for the properties of IHostEnvironment. Available from HostBuilderContext.Configuration inside ConfigureAppConfiguration method.

  • After ConfigureAppConfiguration method, HostBuilderContext.Configuration is set to the app configuration.

Call ConfigureHostConfiguration on IHostBuilder:

Host.CreateDefaultBuilder(args)
    .ConfigureHostConfiguration(hostConfig =>
    {
        hostConfig.SetBasePath(Directory.GetCurrentDirectory());
        hostConfig.AddJsonFile("hostsettings.json", optional: true);
        hostConfig.AddEnvironmentVariables(prefix: "PREFIX_");
        hostConfig.AddCommandLine(args);
    });

App Configuration

Call ConfigureAppConfiguration on IHostBuilder. Available at HostBuilderContext.Configuration and as a service from DI.

Host Settings for All App Types

All of these settings can be set in env vars with DOTNET_ or ASPNETCORE_ prefixes:

KeyDefaultEnvAlternate way to set
applicationName (string)Name of app assemblyPREFIX_APPLICATIONNAMEEnv var
contentRoot (string)Folder of app assemblyPREFIX_CONTENTROOTUseContentRoot on IHostBuilder
environment (string)ProductionPREFIX_ENVIRONMENTUseEnvironment
Can be any value; Development and Staging are common.
shutdownTimeoutSeconds (int)5 secondsPREFIX_SHUTDOWNTIMEOUTSECONDSconfigure HostOptions
Sets timeout for StopAsync
hostBuilder:reloadConfigOnChange (bool)truePREFIX_hostBuilder:reloadConfigOnChangeEnvVar

Host Settings for HTTP Workloads Only

Set via env vars with DOTNET_ or ASPNETCORE_ prefixes or extension methods on IWebHostBuilder:

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webHostBuilder =>
    {
        // ...
    });
KeyDefaultEnv VarAlternate way to set
captureStartupErrors (bool)
If false, errors during startup result in host exit
false
(unless running as Kestrel behind IIS)
PREFIX_CAPTURESTARTUPERRORSwebBuilder.CaptureStartupErrors();
detailedErrors (bool)
Capture detailed errors
Also enabled if environment == Development
falsePREFIX_DETAILEDERRORSwebBuilder.UseSetting(WebHostDefaults.DetailedErrors Key, "true");
hostingStartupAssemblies (string)
Semicolon-delimited string of startup assemblies to load on startup
(empty)PREFIX_HOSTINGSTARTUP
ASSEMBLIES
webBuilder.UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2");
hostingStartupExcludeAssemblies (string)(empty)PREFIX_HOSTING
STARTUPEXCLUDEASSEMBLIES
webBuilder.UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey "assembly1;assembly2");
https_port (string)(empty)PREFIX_HTTPS_PORTwebBuilder.UseSetting("https_port", "8080");
preferHostingUrls (bool)
Listen on URLs configured with IServer
truePREFIX_PREFERHOSTINGURLswebBuilder.PreferHostingUrls(true);
preventHostingStartup (bool)falsePREFIX_PREVENTHOSTINGSTARTUPwebBuilder.UseSetting(WebHostDefaults.PreventHostingStartupKey, "true");
suppressStatusMessages (bool)
Suppress hosting startup status messages.
falsePREFIX_SUPRESSSTATUSMESSAGESwebBuilder.UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "true");
urls (string)
A list of IP addresses or host addresses with ports and
protocols that the server should listen on for requests.
stringPREFIX_URLSwebBuilder.UseUrls("https://*:5000;http://localhost:5001;…");
webroot (string)
The relative path to the app’s static assets
wwwrootPREFIX_WEBROOTwebBuilder.UseWebRoot("public");

Manage the Host Lifetime

Call these methods on IHost:

  • Run — run the app and block the calling thread until host is shut down.
  • RunAsync — run the app and return a Task that completes when cancellation token or shutdown is triggered.
  • RunConsoleAsync — enable console support and waits for Ctrl + C / SIGINT or SIGTERM to shut down.
  • Start — start the host synchronously.
  • StartAsync — start the host and return a Task
  • WaitForStartAsync is called at the start of StartAsync. Use to delay startup until signaled by an external event.
  • StopAsync — stop the host within the provided timeout.
  • WaitForShutdown — blocks the calling thread until shutdown is triggered.
  • WaitForShutdownAsync — returns a Task that completes when shutdown is triggered and calls StopAsync.