.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
  • ConfigurationConfiguration
  • IHostedService 实现IHostedService implementations

启动主机时,它对它在 DI 容器中找到的 IHostedService 的每个实现调用 IHostedService.StartAsyncWhen a host starts, it calls IHostedService.StartAsync on each implementation of IHostedService that it finds in the DI container. 在 web 应用中,其中一个 IHostedService 实现是启动 HTTP 服务器实现的 web 服务。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.json 。appsettings.json.
    • appsettings.{Environment}.json 。appsettings.{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:

有关框架提供的所有服务列表,请参阅 在 ASP.NET Core 依赖注入For a list of all framework-provided services, see 在 ASP.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.Configuration 获取。Host configuration is available from HostBuilderContext.Configuration inside ConfigureAppConfiguration. ConfigureAppConfiguration 后,HostBuilderContext.Configuration 被替换为应用配置。After 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 调用 ConfigureAppConfiguration 创建应用配置。App 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
类型:string Type: 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
类型:string Type: 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. 框架定义的值包括 Development``StagingProductionFramework-defined values include Development, Staging, and Production. 值不区分大小写。Values aren't case sensitive.

:环境Key: environment
类型:string Type: 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. 默认值为 5 秒。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
类型:int Type: 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
类型:布尔型(true1Type: bool (true or 1)
默认值:默认为 false,除非应用使用 Kestrel 在 IIS 后方运行,其中默认值是 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
类型:布尔型(true1Type: 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
类型:string Type: 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
类型:string Type: 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_port;类型:字符串; 默认值 :未设置默认值。Key: https_port Type: 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
类型:布尔型(true1Type: 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
类型:布尔型(true1Type: 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.

:startupAssembly 类型:字符串 Key: startupAssembly Type: 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. 使用“*”指示服务器应针对请求侦听的使用特定端口和协议(例如 http://*:5000)的 IP 地址或主机名。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
类型:string Type: string
默认值http://localhost:5000https://localhost:5001 环境变量<PREFIX_>URLSDefault: http://localhost:5000 and https://localhost:5001 Environment 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 Web 服务器实现For more information, see ASP.NET Core 中的 Kestrel Web 服务器实现.

WebRootWebRoot

应用的静态资产的相对路径。The relative path to the app's static assets.

:webrootKey: webroot
类型:string Type: string
默认:(内容根路径)/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.

StartStart

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.

StartAsync 开始时调用 WaitForStartAsync,在继续之前,会一直等待该操作完成。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 返回在通过给定的令牌和调用 StopAsync 来触发关闭时完成的 TaskWaitForShutdownAsync 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 中的新增功能,不适用于 Web 承载方案。Generic Host is new in ASP.NET Core 2.1 and isn't suitable for web hosting scenarios. 对于 Web 承载方案,请使用 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 启动(控制台)配置中,找到控制台条目 。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

HostOptions 配置 IHost 的选项。HostOptions configure options for the IHost.

关闭超时值Shutdown timeout

ShutdownTimeout 设置 StopAsync 的超时值。ShutdownTimeout sets the timeout for StopAsync. 默认值为 5 秒。The default value is five seconds.

Program.Main 中的以下选项配置将默认值为 5 秒的关闭超时值增加至 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
类型:string Type: 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
类型:string Type: 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.

:环境Key: environment
类型:string Type: 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. 框架定义的值包括 Development``StagingProductionFramework-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.json :hostsettings.json:

{
  "environment": "Development"
}

可以通过 applicationNamecontentRoot 键提供其他配置。Additional configuration can be provided with the applicationName and contentRoot keys.

示例 HostBuilder 配置使用 ConfigureHostConfigurationExample 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 实现上调用 ConfigureAppConfiguration 创建应用配置。App 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.Configuration 中提供 ConfigureAppConfiguration 创建的配置,以供进行后续操作和在 Services 中使用。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.

示例应用配置使用 ConfigureAppConfigurationExample 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.json :appsettings.json:

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

appsettings.Development.json :appsettings.Development.json:

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

appsettings.Production.json :appsettings.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.json :The 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.JsonMicrosoft.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 元包,否则除了核心 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. 可以利用相加结果多次调用 ConfigureLoggingConfigureLogging 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. 可以利用相加结果多次调用 ConfigureContainerConfigureContainer 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 返回在通过给定的令牌和调用 StopAsync 来触发关闭时完成的 TaskWaitForShutdownAsync 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));
        }
    }
}

StartAsync 开始时调用 WaitForStartAsync,在继续之前,会一直等待该操作完成。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.cs :LifetimeEventsHostedService.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