Fundamentals - Host - Generic Host

In this article

Host definition

Set up a host

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

Default builder settings

Framework-provided services

IHostApplicationLifetime

public class HostApplicationLifetimeEventsHostedService : IHostedService
{
    private readonly IHostApplicationLifetime _hostApplicationLifetime;

    public HostApplicationLifetimeEventsHostedService(
        IHostApplicationLifetime hostApplicationLifetime)
        => _hostApplicationLifetime = hostApplicationLifetime;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
        _hostApplicationLifetime.ApplicationStopping.Register(OnStopping);
        _hostApplicationLifetime.ApplicationStopped.Register(OnStopped);

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
        => Task.CompletedTask;

    private void OnStarted()
    {
        // ...
    }

    private void OnStopping()
    {
        // ...
    }

    private void OnStopped()
    {
        // ...
    }
}

IHostLifetime

IHostEnvironment

Host configuration

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

App configuration

Settings for all app types

ApplicationName

ContentRoot

Host.CreateDefaultBuilder(args)
    .UseContentRoot("/path/to/content/root")
    // ...

EnvironmentName

Host.CreateDefaultBuilder(args)
    .UseEnvironment("Development")
    // ...

ShutdownTimeout

Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services.Configure<HostOptions>(options =>
        {
            options.ShutdownTimeout = TimeSpan.FromSeconds(20);
        });
    });

Disable app configuration reload on change

Warning The colon (:) separator doesn't work with environment variable hierarchical keys on all platforms. For more information, see Environment variables.

Settings for web apps

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder =>
    {
        // ...
    });

CaptureStartupErrors

webBuilder.CaptureStartupErrors(true);

DetailedErrors

webBuilder.UseSetting(WebHostDefaults.DetailedErrorsKey, "true");

HostingStartupAssemblies

webBuilder.UseSetting(
    WebHostDefaults.HostingStartupAssembliesKey, "assembly1;assembly2");

HostingStartupExcludeAssemblies

webBuilder.UseSetting(
    WebHostDefaults.HostingStartupExcludeAssembliesKey, "assembly1;assembly2");

HTTPS_Port

webBuilder.UseSetting("https_port", "8080");

PreferHostingUrls

webBuilder.PreferHostingUrls(true);

PreventHostingStartup

webBuilder.UseSetting(WebHostDefaults.PreventHostingStartupKey, "true");

StartupAssembly

webBuilder.UseStartup("StartupAssemblyName");
webBuilder.UseStartup<Startup>();

SuppressStatusMessages

webBuilder.UseSetting(WebHostDefaults.SuppressStatusMessagesKey, "true");

URLs

webBuilder.UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002");

WebRoot

webBuilder.UseWebRoot("public");

Manage the host lifetime

Run

RunAsync

RunConsoleAsync

Start

StartAsync

StopAsync

WaitForShutdown

WaitForShutdownAsync

Additional resources

Note Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Note Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).

Ref: .NET Generic Host in ASP.NET Core