.NET 泛型主機.NET Generic Host

作者:Luke LathamBy Luke Latham

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

本文涵蓋 .NET Core 泛型主機 (HostBuilder)。This article covers the .NET Core Generic Host (HostBuilder).

泛型主機與 Web 主機不同,其會將 HTTP 管線從 Web 主機 API 分離,以允許更廣泛的主機陣列案例。Generic Host differs from Web Host in that it decouples 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 can use Generic Host and benefit from cross-cutting capabilities, such as configuration, dependency injection (DI), and logging.

從 ASP.NET Core 3.0 開始,建議針對 HTTP 和非 HTTP 工作負載使用泛型主機。Starting in ASP.NET Core 3.0, Generic Host is recommended for both HTTP and non-HTTP workloads. HTTP 伺服器實作 (如果包含) 會以 IHostedService 的實作來執行。An HTTP server implementation, if included, runs as an implementation of IHostedService. IHostedService 是也可針對其他工作負載使用的介面。IHostedService is an interface that can be used for other workloads as well.

不再針對 Web 應用程式建議使用 Web 主機,但仍然適用於回溯相容性。Web Host is no longer recommended for web apps but remains available for backward compatibility.

注意

本文的其餘部分尚未更新為 3.0。This remainder of this article hasn't been updated for 3.0.

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.

主機組態會自動流向應用程式組態 (ConfigureAppConfiguration 及剩餘的所有應用程式)。Host configuration automatically flows to app configuration (ConfigureAppConfiguration and the rest of the app).

預設不會包含任何提供者。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