0%

Hosting in .NET Core

在.NET Core中,Host负责应用程序的启动和生命周期管理。除此之外,在Host中还可以设置日志(Logging)、配置(Configuration)和依赖关系注入(Dependency Injection)等。Host将一个常规的控制台应用程序(Console Application)变成了一个可以长时间运行的服务(Long-running Service)。

Hosting History

在.NET Core中,有以下2个Host:

  • .NET Generic Host(简称 Generic Host)
  • ASP.NET Core Web Host(简称 Web Host)

要了解它们之间的区别与联系,我们需要从.NET Core的发展历程中寻找答案。

微软在2016年6月发布了.NET Core 1.0。.NET Core是一个开放的、支持跨平台的框架,它与.NET Framework有着显著的不同。在这之后微软又陆续发布了.NET Core 1.1.NET Core 2.0.NET Core 2.1.NET Core 2.2.NET Core 3.0.NET Core 3.1

Web Host在.NET Core 1.0中被引入,它被用于配置并启动KestrelWeb服务器,在指定的端口上监听HTTP请求。Web Host正如它的名称所言,只用于Host ASP.NET Core Web Application。

Generic Host在.NET Core 2.1中被引入,但它只被用于non-HTTP的场景,例如hosted services/worker services。此时你仍需要使用Web Host来Host ASP.NET Core Web Application。这带来了一定的混淆和麻烦,很多相近的类被引入。

IWebHost 与 IHost,IWebHostBuilder与IHostBuilder

InterfaceNamespaceDefault ImplementationGit RepoSource Code
IWebHostMicrosoft.AspNetCore.HostingWebHosthttps://github.com/dotnet/aspnetcoresrc/Hosting/Hosting/src/Internal/WebHost.cs
IHostMicrosoft.Extensions.HostingHosthttps://github.com/dotnet/runtimesrc/libraries/Microsoft.Extensions.Hosting/src/Internal/Host.cs
IWebHostBuilderMicrosoft.AspNetCore.HostingWebHostBuilderhttps://github.com/dotnet/aspnetcoresrc/Hosting/Hosting/src/WebHostBuilder.cs
IHostBuilderMicrosoft.Extensions.HostingHostBuilderhttps://github.com/dotnet/runtimesrc/libraries/Microsoft.Extensions.Hosting/src/HostBuilder.cs

还有与这些接口相关的静态辅助类:

ClassNamespaceGit RepoSource Code
WebHostMicrosoft.AspNetCorehttps://github.com/dotnet/aspnetcoresrc/DefaultBuilder/src/WebHost.cs
HostMicrosoft.Extensions.Hostinghttps://github.com/dotnet/runtimesrc/libraries/Microsoft.Extensions.Hosting/src/Host.cs

我们在Program.cs文件中一般都是用这两个静态辅助类来创建IWebHost或IHost的具体实例,进而启动应用程序。

IHostingEnvironment vs IHostEnvironment vs IWebHostEnvironment

这几个接口是不是傻傻分不清?这其实充分说明了微软在主导.NET Core的开发过程中存在着管理和命名的混乱。这也难免,毕竟这么大的项目,而且代码库也是各管各的。

首先IHostingEnvironment存在于2个不同的命名空间中,虽然接口内容大致相同,但却是互不兼容的——它们之间没有继承关系。

InterfaceNamespaceGit RepoSource Code
IHostingEnvironmentMicrosoft.AspNetCore.Hostinghttps://github.com/dotnet/aspnetcoresrc/Hosting/Abstractions/src/IHostingEnvironment.cs
IHostingEnvironmentMicrosoft.Extensions.Hostinghttps://github.com/dotnet/runtimesrc/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHostingEnvironment.cs

从.NET Core 3.0起,这两个接口都被标记为obsolete,取而代之的分别是IWebHostEnvironment 与 IHostEnvironment。它们依然存在于不同的命名空间中,但它们之间有了继承关系。

InterfaceNamespaceGit RepoSource Code
IWebHostEnvironmentMicrosoft.AspNetCore.Hostinghttps://github.com/dotnet/aspnetcoresrc/Hosting/Abstractions/src/IWebHostEnvironment.cs
IHostEnvironmentMicrosoft.Extensions.Hostinghttps://github.com/dotnet/runtimesrc/libraries/Microsoft.Extensions.Hosting.Abstractions/src/IHostEnvironment.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace Microsoft.AspNetCore.Hosting
{
public interface IWebHostEnvironment : IHostEnvironment
{
string WebRootPath { get; set; }
IFileProvider WebRootFileProvider { get; set; }
}
}

namespace Microsoft.Extensions.Hosting
{
public interface IHostEnvironment
{
string EnvironmentName { get; set; }
string ApplicationName { get; set; }
string ContentRootPath { get; set; }
IFileProvider ContentRootFileProvider { get; set; }
}
}

这样的设计就很合理,也减少了重复。它们各自的默认实现也基本相同。

Default ImplementationNamespaceGit RepoSource Code
HostingEnvironmentMicrosoft.AspNetCore.Hostinghttps://github.com/dotnet/aspnetcoresrc/Hosting/Hosting/src/Internal/HostingEnvironment.cs
HostingEnvironmentMicrosoft.Extensions.Hosting.Internalhttps://github.com/dotnetsrc/libraries/Microsoft.Extensions.Hosting/src/Internal/HostingEnvironment.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
namespace Microsoft.AspNetCore.Hosting
{
internal class HostingEnvironment : IHostingEnvironment, Extensions.Hosting.IHostingEnvironment,
IWebHostEnvironment
{
public string EnvironmentName { get; set; } = Extensions.Hosting.Environments.Production;
public string ApplicationName { get; set; }
public string WebRootPath { get; set; }
public IFileProvider WebRootFileProvider { get; set; }
public string ContentRootPath { get; set; }
public IFileProvider ContentRootFileProvider { get; set; }
}
}

namespace Microsoft.Extensions.Hosting.Internal
{
public class HostingEnvironment : IHostingEnvironment, IHostEnvironment
{
public string EnvironmentName { get; set; }
public string ApplicationName { get; set; }
public string ContentRootPath { get; set; }
public IFileProvider ContentRootFileProvider { get; set; }
}
}

Generic Host 取代 Web Host

时间来到了.NET Core 3.0发布。微软重构了Generic Host,使之成为一个真正的通用的Host——可同时运行Worker Services和Web Applications。这大大简化了Host的模型及相关的类,开发者理解和使用起来更加容易了。

.NET Core Hosting History图片来自PluralSight课程

小结

  • 尽可能地使用IHostEnvironment
  • 官方不建议在.NET Core 3.0及以上的版本中使用Web Host
  • 对于ASP.NET Core Web Application来说,Kestrel Web Server被包装在GenericWebHostService中被Generic Host初始化启动

微软于2020年11月发布了.NET 5.NET 5是.NET Core的下一个版本,被描述为.NET统一之旅中的第一个版本,它是为了使更多的开发人员能够将.NET框架代码和应用迁移到.NET 5。该平台将来自.NET Framework、.NET Core和Mono的代码组合在一起,为所有现代.NET应用提供一个单一的平台。本文所讨论的.NET Generic Host同样适用于.NET 5

CreateDefaultBuilder与ConfigureWebHostDefaults

一般情况下,我们使用静态辅助类Host中的CreateDefaultBuilder方法来创建IHostBuilder的实例。对于ASP.NET Core Web Application,我们还会调用ConfigureWebHostDefaults方法。我们需要了解这两个方法到底做了哪些默认的设置,以便减少不必要、多余的设置。

CreateDefaultBuilder 方法

  • 将内容根目录设置为由 GetCurrentDirectory 返回的路径
  • 通过以下项加载主机配置:
    • 前缀为 DOTNET_ 的环境变量
    • 命令行参数
  • 通过以下项加载应用配置:
    • appsettings.json
    • appsettings.{Environment}.json
    • 在 Development 环境中运行时的用户机密配置信息(secrets.json)
    • 环境变量
    • 命令行参数
  • 添加以下日志提供程序:
    • 控制台
    • 调试
    • EventSource
    • EventLog(仅当在 Windows 上运行时)
  • 在 Development 环境中,启用范围验证依赖关系验证

HostBuilder Defaults图片来自PluralSight课程

ConfigureWebHostDefaults 方法

  • 从前缀为 ASPNETCORE_ 的环境变量加载主机配置。
  • 使用应用的托管配置提供程序将 Kestrel 服务器设置为 web 服务器并对其进行配置。
  • 如果 ASPNETCORE_FORWARDEDHEADERS_ENABLED 等于 true,则添加转接头中间件(ForwardedHeadersStartupFilter)。
  • 添加 IIS 集成。

推荐阅读源代码了解更多的实现细节

Generic Host 的启动与停止

启动

Generic Host 的启动步骤如下:

  1. Program.cs文件中,通过CreateDefaultBuilder构建一个IHost的实例
  2. 调用IHost上的静态扩展方法Run或RunAsync,这会间接调用到IHostStartAsync方法
  3. IHostStartAsync方法则会遍历所有注册的IHostedService,调用它的StartAsync方法
  4. IHost上的静态扩展方法[Run或RunAsync]会调用另一个扩展方法——WaitForShutdownAsync,等待程序结束的信号

Host Startup图片来自PluralSight课程
.NET Core 应用程序运行后会创建名为.NET Host(dotnet.exe)的后台进程。
.NET Host

停止

Generic Host 的停止步骤如下:

  1. 用户使用Ctrl + C或者应用程序使用代码来发出程序结束的信号
  2. IHostStopAsync方法在WaitForShutdownAsync中被调用
  3. 所有注册的IHostedServiceStopAsync方法被调用
  4. 应用程序退出

Host Shutdown图片来自PluralSight课程
需要指出的是,IHostedService的注册顺序是非常重要的,启动的时候是按注册顺序,停止的时候则是倒序。

其它的Host

在Windows操作系统中,你还会看到很多其它的Host。

Console Window Host(conhost.exe)

Console Window Host, 即命令行程序的宿主进程。典型的命令行程序有cmd.exe、nslookup.exe等。Console Window Host负责绘制命令行程序的图形化窗口,管理输入缓冲区屏幕缓冲区

Service Host(svchost.exe)

Service Host是一个共有的宿主进程的名称,它用来运行DLL文件中的服务,特别是很多系统服务。为了使这些服务之间保持隔离,减少相互影响导致的程序错误,系统会运行很多个Service Host的进程实例。你可以使用Process Explorer这个工具,通过Command Line列来区分它们。

Service Host Process

DLL Host(dllhost.exe)

DLL Host程序又称为COM Surrogate,它是COM组件的宿主进程。COM(Component Object Model,组件对象模型)是微软于1993年提出的一种软件开发技术,它定义了组件对象进行交互的二进制接口标准。COM组件大多以动态链接库(DLL)的形式发布,DLL Host(dllhost.exe)则正是加载这些COM组件的宿主程序。与Service Host类似,系统会运行很多个DLL Host的进程实例。你可以使用Process Explorer这个工具,通过Command Line列来区分它们。

DLL Host Process

参考资料