.NET 泛型主機.NET Generic Host

本文介紹 .NET Core 的泛型主機 (HostBuilder),並提供指導。This article introduces the .NET Core Generic Host (HostBuilder) and provides guidance on how to use it.

什麼是主機?What's a host?

「主機」是封裝所有應用程式資源的物件,例如:A host is an object that encapsulates an app's resources, such as:

  • 相依性插入 (DI)Dependency injection (DI)
  • 記錄Logging
  • 組態Configuration
  • IHostedService 實作IHostedService implementations

當啟動主機時,會在 DI 容器中找到的每個 IHostedService.StartAsync 實作上呼叫 IHostedServiceWhen a host starts, it calls IHostedService.StartAsync on each implementation of IHostedService that it finds in the DI container. 在 Web 應用程式中,其中一個 IHostedService 實作是一種 Web 服務,負責啟動 HTTP 伺服器實作In a web app, one of the IHostedService implementations is a web service that starts an HTTP server implementation.

在單一物件中包含所有應用程式相互依存資源的主要理由便是生命週期管理:控制應用程式的啟動及順利關機。The main reason for including all of the app's interdependent resources in one object is lifetime management: control over app startup and graceful shutdown.

在 3.0 之前版本的 ASP.NET Core 中,Web 主機用於 HTTP 工作負載。In versions of ASP.NET Core earlier than 3.0, the Web Host is used for HTTP workloads. 不再建議將 Web 應用程式用於 Web 主機,且僅維持適用於回溯相容性。The Web Host is no longer recommended for web apps and remains available only for backward compatibility.

設定主機Set up a host

主機通常由 Program 類別的程式碼來設定、建置並執行。The host is typically configured, built, and run by code in the Program class. Main 方法:The Main method:

  • 呼叫 CreateHostBuilder 方法來建立及設定建立器物件。Calls a CreateHostBuilder method to create and configure a builder object.
  • 在建立器物件上呼叫 BuildRun 方法。Calls Build and Run methods on the builder object.

以下是用於非 HTTP 工作負載的 Program.cs 程式碼,其中的單一 IHostedService 實作會新增至 DI 容器。Here's Program.cs code for a non-HTTP workload, with a single IHostedService implementation added to the DI container.

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
               services.AddHostedService<Worker>();
            });
}

針對 HTTP 工作負載,Main 方法相同,但 CreateHostBuilder 會呼叫 ConfigureWebHostDefaultsFor an HTTP workload, the Main method is the same but CreateHostBuilder calls ConfigureWebHostDefaults:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

如果應用程式使用 Entity Framework Core,請勿變更 CreateHostBuilder 方法的名稱或簽章。If the app uses Entity Framework Core, don't change the name or signature of the CreateHostBuilder method. Entity Framework Core 工具預期找到 CreateHostBuilder 方法,其在不執行應用程式的情況下設定主機。The Entity Framework Core tools expect to find a CreateHostBuilder method that configures the host without running the app. 如需詳細資訊,請參閱設計階段 DbContext 建立For more information, see Design-time DbContext Creation.

預設建立器設定Default builder settings

CreateDefaultBuilder 方法:The CreateDefaultBuilder method:

  • 設定 GetCurrentDirectory 所傳回路徑的內容根目錄。Sets the content root to the path returned by GetCurrentDirectory.
  • 從下列項目載入主機組態:Loads host configuration from:
    • 前面加上 "DOTNET_" 的環境變數。Environment variables prefixed with "DOTNET_".
    • 命令列引數。Command-line arguments.
  • 從下列項目載入應用程式組態:Loads app configuration from:
    • appsettings.jsonappsettings.json.
    • appsettings.{Environment}.jsonappsettings.{Environment}.json.
    • 應用程式在 Development 環境中執行時的祕密管理員Secret Manager when the app runs in the Development environment.
    • 環境變數。Environment variables.
    • 命令列引數。Command-line arguments.
  • 新增下列記錄提供者:Adds the following logging providers:
    • 主控台Console
    • 偵錯Debug
    • EventSourceEventSource
    • EventLog (僅當在 Windows 上執行時)EventLog (only when running on Windows)
  • 環境為開發時,會啟用範圍驗證相依性驗證Enables scope validation and dependency validation when the environment is Development.

ConfigureWebHostDefaults 方法:The ConfigureWebHostDefaults method:

本文稍後的<設定所有應用程式類型><Web 應用程式設定>章節,將說明如何覆寫預設的建立器設定。The Settings for all app types and Settings for web apps sections later in this article show how to override default builder settings.

架構提供的服務Framework-provided services

自動註冊的服務包括下列各項:Services that are registered automatically include the following:

如需所有架構提供服務的清單,請參閱 .NET Core 中的相依性插入For a list of all framework-provided services, see .NET Core 中的相依性插入.

IHostApplicationLifetimeIHostApplicationLifetime

IHostApplicationLifetime (先前稱為 IApplicationLifetime) 服務插入任何類別來處理啟動後和順利關機工作。Inject the IHostApplicationLifetime (formerly IApplicationLifetime) service into any class to handle post-startup and graceful shutdown tasks. 介面上的三個屬性是用於註冊應用程式啟動和應用程式關閉事件處理程序方法的取消語彙基元。Three properties on the interface are cancellation tokens used to register app start and app stop event handler methods. 介面也包括 StopApplication 方法。The interface also includes a StopApplication method.

下例為註冊 IApplicationLifetime 事件的 IHostedService 實作:The following example is an IHostedService implementation that registers the IApplicationLifetime events:

internal class LifetimeEventsHostedService : IHostedService
{
    private readonly ILogger _logger;
    private readonly IHostApplicationLifetime _appLifetime;

    public LifetimeEventsHostedService(
        ILogger<LifetimeEventsHostedService> logger, 
        IHostApplicationLifetime appLifetime)
    {
        _logger = logger;
        _appLifetime = appLifetime;
    }

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

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    private void OnStarted()
    {
        _logger.LogInformation("OnStarted has been called.");

        // Perform post-startup activities here
    }

    private void OnStopping()
    {
        _logger.LogInformation("OnStopping has been called.");

        // Perform on-stopping activities here
    }

    private void OnStopped()
    {
        _logger.LogInformation("OnStopped has been called.");

        // Perform post-stopped activities here
    }
}

IHostLifetimeIHostLifetime

IHostLifetime 實作會控制主機啟動及停止的時機。The IHostLifetime implementation controls when the host starts and when it stops. 會使用最後一個註冊的實作。The last implementation registered is used.

ConsoleLifetime 是預設的 IHostLifetime 實作。ConsoleLifetime is the default IHostLifetime implementation. ConsoleLifetimeConsoleLifetime:

IHostEnvironmentIHostEnvironment

會將 IHostEnvironment 服務插入類別以取得下列資訊:Inject the IHostEnvironment service into a class to get information about the following:

Web 應用程式會實作 IWebHostEnvironment 介面,其繼承 IHostEnvironment 並新增:Web apps implement the IWebHostEnvironment interface, which inherits IHostEnvironment and adds:

主機組態Host configuration

主機組態用於 IHostEnvironment 實作的屬性。Host configuration is used for the properties of the IHostEnvironment implementation.

主機組態位於 ConfigureAppConfiguration 內的 HostBuilderContext.ConfigurationHost configuration is available from HostBuilderContext.Configuration inside ConfigureAppConfiguration. ConfigureAppConfiguration 之後,應用程式組態會取代 HostBuilderContext.ConfigurationAfter ConfigureAppConfiguration, HostBuilderContext.Configuration is replaced with the app config.

若要新增主機組態,請呼叫 IHostBuilder 上的 ConfigureHostConfigurationTo add host configuration, call ConfigureHostConfiguration on IHostBuilder. ConfigureHostConfiguration 可以多次呼叫,其結果是累加的。ConfigureHostConfiguration can be called multiple times with additive results. 主機會使用指定索引鍵上最後設定值的任何選項。The host uses whichever option sets a value last on a given key.

CreateDefaultBuilder 包含具有前置詞 DOTNET_ 的環境變數提供者和命令列引數。The environment variable provider with prefix DOTNET_ and command line args are included by CreateDefaultBuilder. 針對 Web 應用程式,會新增具有前置詞 ASPNETCORE_ 的環境變數提供者。For web apps, the environment variable provider with prefix ASPNETCORE_ is added. 讀取環境變數時,就會移除前置詞。The prefix is removed when the environment variables are read. 例如,ASPNETCORE_ENVIRONMENT 的環境變數值會變成 environment 索引鍵的主機組態值。For example, the environment variable value for ASPNETCORE_ENVIRONMENT becomes the host configuration value for the environment key.

下列範例會建立主機組態:The following example creates host configuration:

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

應用程式設定App configuration

應用程式組態的建立方式是在 IHostBuilder 上呼叫 ConfigureAppConfigurationApp configuration is created by calling ConfigureAppConfiguration on IHostBuilder. ConfigureAppConfiguration 可以多次呼叫,其結果是累加的。ConfigureAppConfiguration can be called multiple times with additive results. 應用程式會使用指定索引鍵上最後設定值的任何選項。The app uses whichever option sets a value last on a given key.

ConfigureAppConfiguration 建立的組態位於 HostBuilderContext.Configuration,可用於後續作業並用作 DI 中的服務。The configuration created by ConfigureAppConfiguration is available at HostBuilderContext.Configuration for subsequent operations and as a service from DI. 主機組態也會新增至應用程式組態。The host configuration is also added to the app configuration.

如需詳細資訊,請參閱 ASP.NET Core 中的組態For more information, see Configuration in ASP.NET Core.

所有應用程式類型的設定Settings for all app types

本節列出適用於 HTTP 和非 HTTP 工作負載的主機設定。This section lists host settings that apply to both HTTP and non-HTTP workloads. 根據預設,用來設定這些設定的環境變數可以具有 DOTNET_ASPNETCORE_ 前置詞。By default, environment variables used to configure these settings can have a DOTNET_ or ASPNETCORE_ prefix.

ApplicationNameApplicationName

IHostEnvironment.ApplicationName 屬性是在主機建構期間從主機組態當中設定。The IHostEnvironment.ApplicationName property is set from host configuration during host construction.

索引鍵:applicationNameKey: applicationName
類型stringType: string
預設:包含應用程式進入點的組件名稱。Default: The name of the assembly that contains the app's entry point. 環境變數<PREFIX_>APPLICATIONNAMEEnvironment variable: <PREFIX_>APPLICATIONNAME

若要設定此值,請使用環境變數。To set this value, use the environment variable.

ContentRootPathContentRootPath

IHostEnvironment.ContentRootPath 屬性會決定主機從哪裡開始搜尋內容檔案。The IHostEnvironment.ContentRootPath property determines where the host begins searching for content files. 如果路徑不存在,就無法啟動主機。If the path doesn't exist, the host fails to start.

索引鍵:contentRootKey: contentRoot
類型stringType: string
預設:應用程式組件所在的資料夾。Default: The folder where the app assembly resides.
環境變數<PREFIX_>CONTENTROOTEnvironment variable: <PREFIX_>CONTENTROOT

若要設定此值,請使用環境變數或呼叫 IHostBuilder 上的 UseContentRootTo set this value, use the environment variable or call UseContentRoot on IHostBuilder:

Host.CreateDefaultBuilder(args)
    .UseContentRoot("c:\\content-root")
    //...

EnvironmentNameEnvironmentName

IHostEnvironment.EnvironmentName 屬性可以設為任何值。The IHostEnvironment.EnvironmentName property can be set to any value. 架構定義的值包括 DevelopmentStagingProductionFramework-defined values include Development, Staging, and Production. 值不區分大小寫。Values aren't case sensitive.

索引鍵:environmentKey: environment
類型stringType: string
預設:生產環境Default: Production
環境變數<PREFIX_>ENVIRONMENTEnvironment variable: <PREFIX_>ENVIRONMENT

若要設定此值,請使用環境變數或呼叫 IHostBuilder 上的 UseEnvironmentTo set this value, use the environment variable or call UseEnvironment on IHostBuilder:

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

ShutdownTimeoutShutdownTimeout

HostOptions.ShutdownTimeout 會設定 StopAsync 的逾時。HostOptions.ShutdownTimeout sets the timeout for StopAsync. 預設值是五秒鐘。The default value is five seconds. 在逾時期間,主機會:During the timeout period, the host:

如果在所有的託管服務停止之前逾時期限已到期,則應用程式關閉時,會停止任何剩餘的作用中服務。If the timeout period expires before all of the hosted services stop, any remaining active services are stopped when the app shuts down. 即使服務尚未完成處理也會停止。The services stop even if they haven't finished processing. 如果服務需要更多時間才能停止,請增加逾時。If services require additional time to stop, increase the timeout.

索引鍵:shutdownTimeoutSecondsKey: shutdownTimeoutSeconds
類型intType: int
預設:5 秒環境變數<PREFIX_>SHUTDOWNTIMEOUTSECONDSDefault: 5 seconds Environment variable: <PREFIX_>SHUTDOWNTIMEOUTSECONDS

若要設定此值,請使用環境變數或設定 HostOptionsTo set this value, use the environment variable or configure HostOptions. 下列範例將逾時設為 20 秒:The following example sets the timeout to 20 seconds:

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

Web 應用程式的設定Settings for web apps

某些主機設定僅適用於 HTTP 工作負載。Some host settings apply only to HTTP workloads. 根據預設,用來設定這些設定的環境變數可以具有 DOTNET_ASPNETCORE_ 前置詞。By default, environment variables used to configure these settings can have a DOTNET_ or ASPNETCORE_ prefix.

IWebHostBuilder 上的擴充方法適用於這些設定。Extension methods on IWebHostBuilder are available for these settings. 示範如何呼叫擴充方法的程式碼範例假設 webBuilderIWebHostBuilder 的執行個體,如下列範例所示:Code samples that show how to call the extension methods assume webBuilder is an instance of IWebHostBuilder, as in the following example:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.CaptureStartupErrors(true);
            webBuilder.UseStartup<Startup>();
        });

CaptureStartupErrorsCaptureStartupErrors

當它為 false 時,啟動期間發生的錯誤會導致主機結束。When false, errors during startup result in the host exiting. 當它為 true 時,主機會擷取啟動期間的例外狀況,並嘗試啟動伺服器。When true, the host captures exceptions during startup and attempts to start the server.

索引鍵:captureStartupErrorsKey: captureStartupErrors
類型bool (true1)Type: bool (true or 1)
預設:預設為 false,除非應用程式執行時在 IIS 背後有 Kestrel,此時預設即為 trueDefault: Defaults to false unless the app runs with Kestrel behind IIS, where the default is true.
環境變數<PREFIX_>CAPTURESTARTUPERRORSEnvironment variable: <PREFIX_>CAPTURESTARTUPERRORS

若要設定此值,請使用組態或呼叫 CaptureStartupErrorsTo set this value, use configuration or call CaptureStartupErrors:

webBuilder.CaptureStartupErrors(true);

DetailedErrorsDetailedErrors

啟用時 (或當環境為 Development 時),應用程式會擷取詳細錯誤。When enabled, or when the environment is Development, the app captures detailed errors.

索引鍵:detailedErrorsKey: detailedErrors
類型bool (true1)Type: bool (true or 1)
預設值:falseDefault: false
環境變數<PREFIX_>_DETAILEDERRORSEnvironment variable: <PREFIX_>_DETAILEDERRORS

若要設定此值,請使用組態或呼叫 UseSettingTo set this value, use configuration or call UseSetting:

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

HostingStartupAssembliesHostingStartupAssemblies

在啟動時載入的裝載啟動組件字串,以分號分隔。A semicolon-delimited string of hosting startup assemblies to load on startup. 雖然設定值會預設為空字串,但裝載啟動組件一律會包含應用程式的組件。Although the configuration value defaults to an empty string, the hosting startup assemblies always include the app's assembly. 提供裝載啟動組件時,它們會新增至應用程式的組件,以便在應用程式在啟動時建置其通用服務時載入。When hosting startup assemblies are provided, they're added to the app's assembly for loading when the app builds its common services during startup.

索引鍵:hostingStartupAssembliesKey: hostingStartupAssemblies
類型stringType: string
預設:空字串Default: Empty string
環境變數<PREFIX_>_HOSTINGSTARTUPASSEMBLIESEnvironment variable: <PREFIX_>_HOSTINGSTARTUPASSEMBLIES

若要設定此值,請使用組態或呼叫 UseSettingTo set this value, use configuration or call UseSetting:

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

HostingStartupExcludeAssembliesHostingStartupExcludeAssemblies

在啟動時排除以分號分隔的裝載啟動組件字串。A semicolon-delimited string of hosting startup assemblies to exclude on startup.

索引鍵:hostingStartupExcludeAssembliesKey: hostingStartupExcludeAssemblies
類型stringType: string
預設:空字串Default: Empty string
環境變數<PREFIX_>_HOSTINGSTARTUPEXCLUDEASSEMBLIESEnvironment variable: <PREFIX_>_HOSTINGSTARTUPEXCLUDEASSEMBLIES

若要設定此值,請使用組態或呼叫 UseSettingTo set this value, use configuration or call UseSetting:

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

HTTPS_PortHTTPS_Port

HTTPS 重新導向連接埠。The HTTPS redirect port. 用於強制 HTTPSUsed in enforcing HTTPS.

索引: HTTPs_portKey: https_port
類型stringType: string
預設:未設定預設值。Default: A default value isn't set.
環境變數<PREFIX_>HTTPS_PORTEnvironment variable: <PREFIX_>HTTPS_PORT

若要設定此值,請使用組態或呼叫 UseSettingTo set this value, use configuration or call UseSetting:

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

PreferHostingUrlsPreferHostingUrls

表示主機是否應接聽使用 IWebHostBuilder 設定的 URL,而不是 IServer 實作所設定的 URL。Indicates whether the host should listen on the URLs configured with the IWebHostBuilder instead of those configured with the IServer implementation.

索引鍵:preferHostingUrlsKey: preferHostingUrls
類型bool (true1)Type: bool (true or 1)
預設值:trueDefault: true
環境變數<PREFIX_>_PREFERHOSTINGURLSEnvironment variable: <PREFIX_>_PREFERHOSTINGURLS

若要設定此值,請使用環境變數或呼叫 PreferHostingUrlsTo set this value, use the environment variable or call PreferHostingUrls:

webBuilder.PreferHostingUrls(false);

PreventHostingStartupPreventHostingStartup

可防止自動載入裝載啟動組件,包括應用程式組件所設定的裝載啟動組件。Prevents the automatic loading of hosting startup assemblies, including hosting startup assemblies configured by the app's assembly. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用裝載啟動組件For more information, see 在 ASP.NET Core 中使用裝載啟動組件.

索引鍵preventHostingStartupKey: preventHostingStartup
類型bool (true1)Type: bool (true or 1)
預設值:falseDefault: false
環境變數<PREFIX_>_PREVENTHOSTINGSTARTUPEnvironment variable: <PREFIX_>_PREVENTHOSTINGSTARTUP

若要設定此值,請使用環境變數或呼叫 UseSettingTo set this value, use the environment variable or call UseSetting :

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

StartupAssemblyStartupAssembly

要搜尋 Startup 類別的組件。The assembly to search for the Startup class.

索引鍵:startupAssemblyKey: startupAssembly
類型stringType: string
預設:應用程式的組件Default: The app's assembly
環境變數<PREFIX_>STARTUPASSEMBLYEnvironment variable: <PREFIX_>STARTUPASSEMBLY

若要設定此值,請使用環境變數或呼叫 UseStartupTo set this value, use the environment variable or call UseStartup. UseStartup 可以採用組件名稱 (string) 或類型 (TStartup)。UseStartup can take an assembly name (string) or a type (TStartup). 如果呼叫多個 UseStartup 方法,最後一個將會優先。If multiple UseStartup methods are called, the last one takes precedence.

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

URLURLs

以分號分隔的 IP 位址或主機位址,包含伺服器應接聽要求的連接埠和通訊協定。A semicolon-delimited list of IP addresses or host addresses with ports and protocols that the server should listen on for requests. 例如: http://localhost:123For example, http://localhost:123. 使用 "*",表示伺服器應接聽任何 IP 位址或主機名稱上的要求,並使用指定的連接埠和通訊協定 (例如,http://*:5000)。Use "*" to indicate that the server should listen for requests on any IP address or hostname using the specified port and protocol (for example, http://*:5000). 通訊協定 (http://https://) 必須包含在每個 URL 中。The protocol (http:// or https://) must be included with each URL. 支援的格式會依伺服器而有所不同。Supported formats vary among servers.

索引鍵:urlsKey: urls
類型stringType: string
預設http://localhost:5000https://localhost:5001Default: http://localhost:5000 and https://localhost:5001
環境變數<PREFIX_>URLSEnvironment variable: <PREFIX_>URLS

若要設定此值,請使用環境變數或呼叫 UseUrlsTo set this value, use the environment variable or call UseUrls:

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

Kestrel 有它自己的端點設定 API。Kestrel has its own endpoint configuration API. 如需詳細資訊,請參閱 ASP.NET Core 中的 Kestrel 網頁伺服器實作For more information, see ASP.NET Core 中的 Kestrel 網頁伺服器實作.

WebRootWebRoot

應用程式靜態資產的相對路徑。The relative path to the app's static assets.

索引鍵:webrootKey: webroot
類型stringType: string
預設(Content Root)/wwwroot (如果路徑存在)。Default: (Content Root)/wwwroot, if the path exists. 如果路徑不存在,則會使用無作業檔案提供者。If the path doesn't exist, a no-op file provider is used.
環境變數<PREFIX_>WEBROOTEnvironment variable: <PREFIX_>WEBROOT

若要設定此值,請使用環境變數或呼叫 UseWebRootTo set this value, use the environment variable or call UseWebRoot:

webBuilder.UseWebRoot("public");

管理主機存留期Manage the host lifetime

在建置的 IHost 實作上呼叫方法來啟動和停止應用程式。Call methods on the built IHost implementation to start and stop the app. 這些方法會影響所有在服務容器中註冊的 IHostedService 實作。These methods affect all IHostedService implementations that are registered in the service container.

執行Run

Run 會執行應用程式並封鎖呼叫執行緒,直到主機關閉為止。Run runs the app and blocks the calling thread until the host is shut down.

RunAsyncRunAsync

RunAsync 會執行應用程式,並傳回觸發取消語彙基元或關機時所完成的 TaskRunAsync runs the app and returns a Task that completes when the cancellation token or shutdown is triggered.

RunConsoleAsyncRunConsoleAsync

RunConsoleAsync 會啟用主控台支援、建置和啟動主機,以及等候 Ctrl+C/SIGINT 或 SIGTERM 關機。RunConsoleAsync enables console support, builds and starts the host, and waits for Ctrl+C/SIGINT or SIGTERM to shut down.

啟動Start

Start 會同步啟動主機。Start starts the host synchronously.

StartAsyncStartAsync

StartAsync 會啟動主機,並傳回觸發取消語彙基元或關機時所完成的 TaskStartAsync starts the host and returns a Task that completes when the cancellation token or shutdown is triggered.

WaitForStartAsyncStartAsync 開始時呼叫,並等到完成後再繼續進行。WaitForStartAsync is called at the start of StartAsync, which waits until it's complete before continuing. 這可用來將啟動延遲到外部事件發出訊號為止。This can be used to delay startup until signaled by an external event.

StopAsyncStopAsync

StopAsync 會嘗試在提供的逾時內停止主機。StopAsync attempts to stop the host within the provided timeout.

WaitForShutdownWaitForShutdown

WaitForShutdown 會封鎖呼叫執行緒,直到 IHostLifetime 觸發關閉為止,例如透過 CTRL-C/SIGINT 或 SIGTERM。WaitForShutdown blocks the calling thread until shutdown is triggered by the IHostLifetime, such as via Ctrl+C/SIGINT or SIGTERM.

WaitForShutdownAsyncWaitForShutdownAsync

WaitForShutdownAsync 會傳回透過指定語彙基元觸發關機時所完成的 Task,並呼叫 StopAsyncWaitForShutdownAsync returns a Task that completes when shutdown is triggered via the given token and calls StopAsync.

外部控制External control

主機存留期直接控制可以使用可從外部呼叫的方法來達成:Direct control of the host lifetime can be achieved using methods that can be called externally:

public class Program
{
    private IHost _host;

    public Program()
    {
        _host = new HostBuilder()
            .Build();
    }

    public async Task StartAsync()
    {
        _host.StartAsync();
    }

    public async Task StopAsync()
    {
        using (_host)
        {
            await _host.StopAsync(TimeSpan.FromSeconds(5));
        }
    }
}

ASP.NET Core 應用程式會設定並啟動主機。ASP.NET Core apps configure and launch a host. 主機負責應用程式啟動和存留期管理。The host is responsible for app startup and lifetime management.

本文所涵蓋的 ASP.NET Core 泛型主機 (HostBuilder),可用來不會處理 HTTP 要求的應用程式。This article covers the ASP.NET Core Generic Host (HostBuilder), which is used for apps that don't process HTTP requests.

泛型主機的用途是將 HTTP 管線從 Web 主機 API 分離,以允許更廣泛的主機陣列案例。The purpose of Generic Host is to decouple the HTTP pipeline from the Web Host API to enable a wider array of host scenarios. 傳訊、背景工作及其他以泛型主機為基礎的非 HTTP 工作負載都受益於跨領域的功能,例如設定、相依性插入 (DI) 和記錄。Messaging, background tasks, and other non-HTTP workloads based on Generic Host benefit from cross-cutting capabilities, such as configuration, dependency injection (DI), and logging.

泛型主機是 ASP.NET Core 2.1 的新功能,不適用於虛擬主機案例。Generic Host is new in ASP.NET Core 2.1 and isn't suitable for web hosting scenarios. 針對虛擬主機案例,請使用 Web 主機For web hosting scenarios, use the Web Host. 泛型主機將在未來版本中取代 Web 主機,並成為 HTTP 和非 HTTP 案例中的主要主機 API。Generic Host will replace Web Host in a future release and act as the primary host API in both HTTP and non-HTTP scenarios.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

Visual Studio Code 中執行範例應用程式時,請使用「外部或整合式終端機」。When running the sample app in Visual Studio Code, use an external or integrated terminal. 請勿在 internalConsole 中執行範例。Don't run the sample in an internalConsole.

若要在 Visual Studio Code 中設定主控台:To set the console in Visual Studio Code:

  1. 開啟 .vscode/launch.json 檔案。Open the .vscode/launch.json file.
  2. 在 [.NET Core Launch (console)] (.NET Core 啟動 (主控台)) 設定中,尋找 console 項目。In the .NET Core Launch (console) configuration, locate the console entry. 將此值設定為 externalTerminalintegratedTerminalSet the value to either externalTerminal or integratedTerminal.

簡介Introduction

可使用位於 Microsoft.Extensions.Hosting 命名空間的泛型主機程式庫,且該程式庫由 Microsoft.Extensions.Hosting 套件提供。The Generic Host library is available in the Microsoft.Extensions.Hosting namespace and provided by the Microsoft.Extensions.Hosting package. Microsoft.AspNetCore.App 中繼套件 (ASP.NET Core 2.1 或更新版本) 包含 Microsoft.Extensions.Hosting 套件。The Microsoft.Extensions.Hosting package is included in the Microsoft.AspNetCore.App metapackage (ASP.NET Core 2.1 or later).

IHostedService 是程式碼執行的進入點。IHostedService is the entry point to code execution. 每個 IHostedService 實作會依 ConfigureServices 中的服務註冊順序執行。Each IHostedService implementation is executed in the order of service registration in ConfigureServices. 當主機啟動時,會在每個 IHostedService 上呼叫 StartAsync;當主機順利關閉時,則會依反向註冊順序呼叫 StopAsyncStartAsync is called on each IHostedService when the host starts, and StopAsync is called in reverse registration order when the host shuts down gracefully.

設定主機Set up a host

IHostBuilder 是程式庫和應用程式用來初始化、建置及執行主機的主要元件:IHostBuilder is the main component that libraries and apps use to initialize, build, and run the host:

public static async Task Main(string[] args)
{
    var host = new HostBuilder()
        .Build();

    await host.RunAsync();
}

選項Options

IHostHostOptions 設定選項。HostOptions configure options for the IHost.

關機逾時Shutdown timeout

ShutdownTimeout 會為 StopAsync 設定逾時。ShutdownTimeout sets the timeout for StopAsync. 預設值是五秒鐘。The default value is five seconds.

Program.Main 中的下列選項設定可將預設的五秒鐘關機逾時增加到 20 秒:The following option configuration in Program.Main increases the default five second shutdown timeout to 20 seconds:

var host = new HostBuilder()
    .ConfigureServices((hostContext, services) =>
    {
        services.Configure<HostOptions>(option =>
        {
            option.ShutdownTimeout = System.TimeSpan.FromSeconds(20);
        });
    })
    .Build();

預設服務Default services

下列服務會在主機初始化期間註冊:The following services are registered during host initialization:

主機組態Host configuration

主機組態的建立方式:Host configuration is created by:

擴充方法Extension methods

應用程式索引鍵 (名稱)Application key (name)

IHostingEnvironment.ApplicationName 屬性是在主機建構期間從主機設定當中設定。The IHostingEnvironment.ApplicationName property is set from host configuration during host construction. 若要明確設定該值,請使用 HostDefaults.ApplicationKeyTo set the value explicitly, use the HostDefaults.ApplicationKey:

索引鍵:applicationNameKey: applicationName
類型stringType: string
預設:包含應用程式進入點的組件名稱。Default: The name of the assembly containing the app's entry point.
設定使用HostBuilderContext.HostingEnvironment.ApplicationNameSet using: HostBuilderContext.HostingEnvironment.ApplicationName
環境變數<PREFIX_>APPLICATIONNAME (<PREFIX_>選擇性和使用者定義的)Environment variable: <PREFIX_>APPLICATIONNAME (<PREFIX_> is optional and user-defined)

內容根目錄Content root

此設定可決定主機開始搜尋內容檔案的位置。This setting determines where the host begins searching for content files.

索引鍵:contentRootKey: contentRoot
類型stringType: string
預設:預設為應用程式組件所在的資料夾。Default: Defaults to the folder where the app assembly resides.
設定使用UseContentRootSet using: UseContentRoot
環境變數<PREFIX_>CONTENTROOT (<PREFIX_>選擇性和使用者定義的)Environment variable: <PREFIX_>CONTENTROOT (<PREFIX_> is optional and user-defined)

如果路徑不存在,就無法啟動主機。If the path doesn't exist, the host fails to start.

var host = new HostBuilder()
    .UseContentRoot("c:\\<content-root>")

環境Environment

設定應用程式的環境Sets the app's environment.

索引鍵:environmentKey: environment
類型stringType: string
預設:生產環境Default: Production
設定使用UseEnvironmentSet using: UseEnvironment
環境變數<PREFIX_>ENVIRONMENT (<PREFIX_>選擇性和使用者定義的)Environment variable: <PREFIX_>ENVIRONMENT (<PREFIX_> is optional and user-defined)

環境可以設定為任何值。The environment can be set to any value. 架構定義的值包括 DevelopmentStagingProductionFramework-defined values include Development, Staging, and Production. 值不區分大小寫。Values aren't case sensitive.

var host = new HostBuilder()
    .UseEnvironment(EnvironmentName.Development)

ConfigureHostConfigurationConfigureHostConfiguration

ConfigureHostConfiguration 會使用 IConfigurationBuilder 來建立主機的 IConfigurationConfigureHostConfiguration uses an IConfigurationBuilder to create an IConfiguration for the host. 主機組態會用來將 IHostingEnvironment 初始化,使其在應用程式建置流程中可供使用。The host configuration is used to initialize the IHostingEnvironment for use in the app's build process.

ConfigureHostConfiguration 可以多次呼叫,其結果是累加的。ConfigureHostConfiguration can be called multiple times with additive results. 主機會使用指定索引鍵上最後設定值的任何選項。The host uses whichever option sets a value last on a given key.

預設不會包含任何提供者。No providers are included by default. 您必須明確地指定應用程式在 ConfigureHostConfiguration 之中需要哪個組態提供者,包括:You must explicitly specify whatever configuration providers the app requires in ConfigureHostConfiguration, including:

  • 檔案組態 (例如,來自 hostsettings.json 的檔案)。File configuration (for example, from a hostsettings.json file).
  • 環境變數組態。Environment variable configuration.
  • 命令列引數組態。Command-line argument configuration.
  • 任何其他必要的組態提供者。Any other required configuration providers.

使用之後呼叫檔案組態提供者SetBasePath,並透過指定應用程式基底路徑,就可使用主機的檔案設定。File configuration of the host is enabled by specifying the app's base path with SetBasePath followed by a call to one of the file configuration providers. 範例應用程式會使用 JSON 檔案,hostsettings.json,並呼叫 AddJsonFile 取用檔案的主機組態設定。The sample app uses a JSON file, hostsettings.json, and calls AddJsonFile to consume the file's host configuration settings.

若要新增主機的環境變數組態,請在主機建立器上呼叫 AddEnvironmentVariablesTo add environment variable configuration of the host, call AddEnvironmentVariables on the host builder. AddEnvironmentVariables 可接受選擇性的使用者定義前置詞。AddEnvironmentVariables accepts an optional user-defined prefix. 範例應用程式會使用前置詞 PREFIX_The sample app uses a prefix of PREFIX_. 讀取環境變數時,就會移除前置詞。The prefix is removed when the environment variables are read. 在設定範例應用程式的主機時,PREFIX_ENVIRONMENT 的環境變數值會變成 environment 索引鍵的主機組態值。When the sample app's host is configured, the environment variable value for PREFIX_ENVIRONMENT becomes the host configuration value for the environment key.

在開發期間使用 Visual Studio 或以 dotnet run 執行應用程式時,可能會在 Properties/launchSettings.json 檔案中設定環境變數。During development when using Visual Studio or running an app with dotnet run, environment variables may be set in the Properties/launchSettings.json file. Visual Studio Code 中,可以在開發期間於 .vscode/launch.json 檔案中設定環境變數。In Visual Studio Code, environment variables may be set in the .vscode/launch.json file during development. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

命令列組態可透過呼叫 AddCommandLine 新增。Command-line configuration is added by calling AddCommandLine. 命令列組態會在最後新增,以便命令列引數覆寫由先前組態提供者提供的組態。Command-line configuration is added last to permit command-line arguments to override configuration provided by the earlier configuration providers.

hostsettings.jsonhostsettings.json:

{
  "environment": "Development"
}

您可以使用 applicationNamecontentRoot 索引鍵來提供其他組態。Additional configuration can be provided with the applicationName and contentRoot keys.

使用 ConfigureHostConfigurationHostBuilder 組態範例:Example HostBuilder configuration using ConfigureHostConfiguration:

var host = new HostBuilder()
    .ConfigureHostConfiguration(configHost =>
    {
        configHost.SetBasePath(Directory.GetCurrentDirectory());
        configHost.AddJsonFile("hostsettings.json", optional: true);
        configHost.AddEnvironmentVariables(prefix: "PREFIX_");
        configHost.AddCommandLine(args);
    })

ConfigureAppConfigurationConfigureAppConfiguration

應用程式組態的建立方式是在 IHostBuilder 實作上呼叫 ConfigureAppConfigurationApp configuration is created by calling ConfigureAppConfiguration on the IHostBuilder implementation. ConfigureAppConfiguration 會使用 IConfigurationBuilder 來建立應用程式的 IConfigurationConfigureAppConfiguration uses an IConfigurationBuilder to create an IConfiguration for the app. ConfigureAppConfiguration 可以多次呼叫,其結果是累加的。ConfigureAppConfiguration can be called multiple times with additive results. 應用程式會使用指定索引鍵上最後設定值的任何選項。The app uses whichever option sets a value last on a given key. 您可以從後續作業的 HostBuilderContext.ConfigurationServices 中存取 ConfigureAppConfiguration 所建立的組態。The configuration created by ConfigureAppConfiguration is available at HostBuilderContext.Configuration for subsequent operations and in Services.

應用程式組態會自動接收由 ConfigureHostConfiguration 提供的主機組態。App configuration automatically receives host configuration provided by ConfigureHostConfiguration.

使用 ConfigureAppConfiguration 的應用程式組態範例:Example app configuration using ConfigureAppConfiguration:

var host = new HostBuilder()
    .ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.SetBasePath(Directory.GetCurrentDirectory());
        configApp.AddJsonFile("appsettings.json", optional: true);
        configApp.AddJsonFile(
            $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", 
            optional: true);
        configApp.AddEnvironmentVariables(prefix: "PREFIX_");
        configApp.AddCommandLine(args);
    })

appsettings.jsonappsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

appsettings.Development.jsonappsettings.Development.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

appsettings.Production.jsonappsettings.Production.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Error",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

若要將設定檔移至輸出目錄,請在專案檔中將設定檔指定為 MSBuild 專案項目To move settings files to the output directory, specify the settings files as MSBuild project items in the project file. 範例應用程式使用下列 <Content> 項目,移動其 JSON 應用程式設定檔和 hostsettings.jsonThe sample app moves its JSON app settings files and hostsettings.json with the following <Content> item:

<ItemGroup>
  <Content Include="**\*.json" Exclude="bin\**\*;obj\**\*" 
      CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

注意

組態擴充方法 (例如 AddJsonFileAddEnvironmentVariables) 需要其他的 NuGet 套件,例如 Microsoft.Extensions.Configuration.Json (英文) 和Microsoft.Extensions.Configuration.EnvironmentVariables (英文)。Configuration extension methods, such as AddJsonFile and AddEnvironmentVariables require additional NuGet packages, such as Microsoft.Extensions.Configuration.Json and Microsoft.Extensions.Configuration.EnvironmentVariables. 除非應用程式使用 Microsoft.AspNetCore.App metapackage,否則,除了核心 Microsoft.Extensions.Configuration (英文) 套件,還必須將這些套件新增至專案。Unless the app uses the Microsoft.AspNetCore.App metapackage, these packages must be added to the project in addition to the core Microsoft.Extensions.Configuration package. 如需詳細資訊,請參閱 ASP.NET Core 的設定For more information, see ASP.NET Core 的設定.

ConfigureServicesConfigureServices

ConfigureServices 會將服務新增至應用程式的相依性插入容器。ConfigureServices adds services to the app's dependency injection container. ConfigureServices 可以多次呼叫,其結果是累加的。ConfigureServices can be called multiple times with additive results.

託管服務是具有背景工作邏輯的類別,可實作 IHostedService 介面。A hosted service is a class with background task logic that implements the IHostedService interface. 如需詳細資訊,請參閱 在 ASP.NET Core 中使用託管服務的背景工作For more information, see 在 ASP.NET Core 中使用託管服務的背景工作.

範例應用程式使用 AddHostedService 擴充方法,將存留期事件 LifetimeEventsHostedService 和計時背景工作 TimedHostedService 等服務新增至應用程式:The sample app uses the AddHostedService extension method to add a service for lifetime events, LifetimeEventsHostedService, and a timed background task, TimedHostedService, to the app:

var host = new HostBuilder()
    .ConfigureServices((hostContext, services) =>
    {
        if (hostContext.HostingEnvironment.IsDevelopment())
        {
            // Development service configuration
        }
        else
        {
            // Non-development service configuration
        }

        services.AddHostedService<LifetimeEventsHostedService>();
        services.AddHostedService<TimedHostedService>();
    })

ConfigureLoggingConfigureLogging

ConfigureLogging 會新增委派以設定提供的 ILoggingBuilderConfigureLogging adds a delegate for configuring the provided ILoggingBuilder. ConfigureLogging 可以多次呼叫,其結果是累加的。ConfigureLogging may be called multiple times with additive results.

var host = new HostBuilder()
    .ConfigureLogging((hostContext, configLogging) =>
    {
        configLogging.AddConsole();
        configLogging.AddDebug();
    })

UseConsoleLifetimeUseConsoleLifetime

UseConsoleLifetime 會接聽 Ctrl+C/SIGINT 或 SIGTERM,並呼叫 StopApplication 以啟動關機程序。UseConsoleLifetime listens for Ctrl+C/SIGINT or SIGTERM and calls StopApplication to start the shutdown process. UseConsoleLifetime 會解除封鎖 RunAsyncWaitForShutdownAsync 等延伸模組。UseConsoleLifetime unblocks extensions such as RunAsync and WaitForShutdownAsync. ConsoleLifetime 會預先註冊為預設存留期實作。ConsoleLifetime is pre-registered as the default lifetime implementation. 系統會使用最後一個註冊的存留期。The last lifetime registered is used.

var host = new HostBuilder()
    .UseConsoleLifetime()

容器設定Container configuration

為支援插入其他容器,主機可以接受 IServiceProviderFactory<TContainerBuilder>To support plugging in other containers, the host can accept an IServiceProviderFactory<TContainerBuilder>. 提供處理站不是 DI 容器註冊的一部分,而是用來建立實體 DI 容器的主機內建功能。Providing a factory isn't part of the DI container registration but is instead a host intrinsic used to create the concrete DI container. UseServiceProviderFactory(IServiceProviderFactory<TContainerBuilder>) 會覆寫用來建立應用程式服務提供者的預設處理站。UseServiceProviderFactory(IServiceProviderFactory<TContainerBuilder>) overrides the default factory used to create the app's service provider.

自訂容器組態由 ConfigureContainer 方法管理。Custom container configuration is managed by the ConfigureContainer method. ConfigureContainer 提供在基礎主機 API 上設定容器的強型別體驗。ConfigureContainer provides a strongly-typed experience for configuring the container on top of the underlying host API. ConfigureContainer 可以多次呼叫,其結果是累加的。ConfigureContainer can be called multiple times with additive results.

建立應用程式的服務容器:Create a service container for the app:

namespace GenericHostSample
{
    internal class ServiceContainer
    {
    }
}

提供服務容器處理站:Provide a service container factory:

using System;
using Microsoft.Extensions.DependencyInjection;

namespace GenericHostSample
{
    internal class ServiceContainerFactory : 
        IServiceProviderFactory<ServiceContainer>
    {
        public ServiceContainer CreateBuilder(
            IServiceCollection services)
        {
            return new ServiceContainer();
        }

        public IServiceProvider CreateServiceProvider(
            ServiceContainer containerBuilder)
        {
            throw new NotImplementedException();
        }
    }
}

使用處理站,並設定應用程式的自訂服務容器:Use the factory and configure the custom service container for the app:

var host = new HostBuilder()
    .UseServiceProviderFactory<ServiceContainer>(new ServiceContainerFactory())
    .ConfigureContainer<ServiceContainer>((hostContext, container) =>
    {
    })

擴充性Extensibility

主機擴充性是透過 IHostBuilder 上的擴充方法執行。Host extensibility is performed with extension methods on IHostBuilder. 下列範例使用 在 ASP.NET Core 中使用託管服務的背景工作 中示範的 TimedHostedService 範例顯示擴充方法如何擴充 IHostBuilder 實作。The following example shows how an extension method extends an IHostBuilder implementation with the TimedHostedService example demonstrated in 在 ASP.NET Core 中使用託管服務的背景工作.

var host = new HostBuilder()
    .UseHostedService<TimedHostedService>()
    .Build();

await host.StartAsync();

應用程式會建立 UseHostedService 擴充方法以註冊在 T 中傳遞的裝載服務:An app establishes the UseHostedService extension method to register the hosted service passed in T:

using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public static class Extensions
{
    public static IHostBuilder UseHostedService<T>(this IHostBuilder hostBuilder)
        where T : class, IHostedService, IDisposable
    {
        return hostBuilder.ConfigureServices(services =>
            services.AddHostedService<T>());
    }
}

管理主機Manage the host

IHost 實作負責啟動及停止服務容器中已註冊的 IHostedService 實作。The IHost implementation is responsible for starting and stopping the IHostedService implementations that are registered in the service container.

執行Run

Run 會執行應用程式並封鎖呼叫執行緒,直到主機關閉為止:Run runs the app and blocks the calling thread until the host is shut down:

public class Program
{
    public void Main(string[] args)
    {
        var host = new HostBuilder()
            .Build();

        host.Run();
    }
}

RunAsyncRunAsync

RunAsync 會執行應用程式,並傳回觸發取消語彙基元或關機時所完成的 TaskRunAsync runs the app and returns a Task that completes when the cancellation token or shutdown is triggered:

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
            .Build();

        await host.RunAsync();
    }
}

RunConsoleAsyncRunConsoleAsync

RunConsoleAsync 會啟用主控台支援、建置和啟動主機,以及等候 Ctrl+C/SIGINT 或 SIGTERM 關機。RunConsoleAsync enables console support, builds and starts the host, and waits for Ctrl+C/SIGINT or SIGTERM to shut down.

public class Program
{
    public static async Task Main(string[] args)
    {
        var hostBuilder = new HostBuilder();

        await hostBuilder.RunConsoleAsync();
    }
}

Start 和 StopAsyncStart and StopAsync

Start 會同步啟動主機。Start starts the host synchronously.

StopAsync 會嘗試在提供的逾時內停止主機。StopAsync attempts to stop the host within the provided timeout.

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
            .Build();

        using (host)
        {
            host.Start();

            await host.StopAsync(TimeSpan.FromSeconds(5));
        }
    }
}

StartAsync 和 StopAsyncStartAsync and StopAsync

StartAsync 會啟動應用程式。StartAsync starts the app.

StopAsync 會停止應用程式。StopAsync stops the app.

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
            .Build();

        using (host)
        {
            await host.StartAsync();

            await host.StopAsync();
        }
    }
}

WaitForShutdownWaitForShutdown

WaitForShutdown 會透過 IHostLifetime 觸發,例如 ConsoleLifetime (會接聽 Ctrl+C/SIGINT 或 SIGTERM)。WaitForShutdown is triggered via the IHostLifetime, such as ConsoleLifetime (listens for Ctrl+C/SIGINT or SIGTERM). WaitForShutdown 會呼叫 StopAsyncWaitForShutdown calls StopAsync.

public class Program
{
    public void Main(string[] args)
    {
        var host = new HostBuilder()
            .Build();

        using (host)
        {
            host.Start();

            host.WaitForShutdown();
        }
    }
}

WaitForShutdownAsyncWaitForShutdownAsync

WaitForShutdownAsync 會傳回透過指定語彙基元觸發關機時所完成的 Task,並呼叫 StopAsyncWaitForShutdownAsync returns a Task that completes when shutdown is triggered via the given token and calls StopAsync.

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = new HostBuilder()
            .Build();

        using (host)
        {
            await host.StartAsync();

            await host.WaitForShutdownAsync();
        }

    }
}

外部控制External control

主機的外部控制可以使用可從外部呼叫的方法來達成:External control of the host can be achieved using methods that can be called externally:

public class Program
{
    private IHost _host;

    public Program()
    {
        _host = new HostBuilder()
            .Build();
    }

    public async Task StartAsync()
    {
        _host.StartAsync();
    }

    public async Task StopAsync()
    {
        using (_host)
        {
            await _host.StopAsync(TimeSpan.FromSeconds(5));
        }
    }
}

WaitForStartAsyncStartAsync 開始時呼叫,並等到完成後再繼續進行。WaitForStartAsync is called at the start of StartAsync, which waits until it's complete before continuing. 這可用來將啟動延遲到外部事件發出訊號為止。This can be used to delay startup until signaled by an external event.

IHostingEnvironment 介面IHostingEnvironment interface

IHostingEnvironment 提供應用程式主控環境的相關資訊。IHostingEnvironment provides information about the app's hosting environment. 使用建構函式插入以取得 IHostingEnvironment,才能使用其屬性和擴充方法:Use constructor injection to obtain the IHostingEnvironment in order to use its properties and extension methods:

public class MyClass
{
    private readonly IHostingEnvironment _env;

    public MyClass(IHostingEnvironment env)
    {
        _env = env;
    }

    public void DoSomething()
    {
        var environmentName = _env.EnvironmentName;
    }
}

如需詳細資訊,請參閱 在 ASP.NET Core 中使用多個環境For more information, see 在 ASP.NET Core 中使用多個環境.

IApplicationLifetime 介面IApplicationLifetime interface

IApplicationLifetime 允許啟動後和關機活動,包括順利關機要求。IApplicationLifetime allows for post-startup and shutdown activities, including graceful shutdown requests. 在介面上的三個屬性是用來註冊定義啟動和關閉事件之 Action 方法的取消語彙基元。Three properties on the interface are cancellation tokens used to register Action methods that define startup and shutdown events.

取消語彙基元Cancellation Token 觸發時機…Triggered when…
ApplicationStarted 已完全啟動主機。The host has fully started.
ApplicationStopped 主機正在完成正常關機程序。The host is completing a graceful shutdown. 應該處理所有要求。All requests should be processed. 關機封鎖,直到完成此事件。Shutdown blocks until this event completes.
ApplicationStopping 主機正在執行正常關機程序。The host is performing a graceful shutdown. 可能仍在處理要求。Requests may still be processing. 關機封鎖,直到完成此事件。Shutdown blocks until this event completes.

建構函式將 IApplicationLifetime 服務插入任何類別。Constructor-inject the IApplicationLifetime service into any class. 範例應用程式使用建構函式插入 LifetimeEventsHostedService 類別 (IHostedService 實作) 來註冊事件。The sample app uses constructor injection into a LifetimeEventsHostedService class (an IHostedService implementation) to register the events.

LifetimeEventsHostedService.csLifetimeEventsHostedService.cs:

internal class LifetimeEventsHostedService : IHostedService
{
    private readonly ILogger _logger;
    private readonly IApplicationLifetime _appLifetime;

    public LifetimeEventsHostedService(
        ILogger<LifetimeEventsHostedService> logger, 
        IApplicationLifetime appLifetime)
    {
        _logger = logger;
        _appLifetime = appLifetime;
    }

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

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    private void OnStarted()
    {
        _logger.LogInformation("OnStarted has been called.");

        // Perform post-startup activities here
    }

    private void OnStopping()
    {
        _logger.LogInformation("OnStopping has been called.");

        // Perform on-stopping activities here
    }

    private void OnStopped()
    {
        _logger.LogInformation("OnStopped has been called.");

        // Perform post-stopped activities here
    }
}

StopApplication 會要求應用程式終止。StopApplication requests termination of the app. 當呼叫類別的 Shutdown 方法時,下列類別使用 StopApplication 來順利關閉應用程式:The following class uses StopApplication to gracefully shut down an app when the class's Shutdown method is called:

public class MyClass
{
    private readonly IApplicationLifetime _appLifetime;

    public MyClass(IApplicationLifetime appLifetime)
    {
        _appLifetime = appLifetime;
    }

    public void Shutdown()
    {
        _appLifetime.StopApplication();
    }
}

其他資源Additional resources