在 ASP.NET Core 中使用承载启动程序集Use hosting startup assemblies in ASP.NET Core

作者:Luke LathamPavel KrymetsBy Luke Latham and Pavel Krymets

通过 IHostingStartup(承载启动)实现,在启动时从外部程序集向应用添加增强功能。An IHostingStartup (hosting startup) implementation adds enhancements to an app at startup from an external assembly. 例如,外部库可使用承载启动实现为应用提供其他配置提供程序或服务。For example, an external library can use a hosting startup implementation to provide additional configuration providers or services to an app.

查看或下载示例代码如何下载View or download sample code (how to download)

HostingStartup 属性HostingStartup attribute

HostingStartup 属性表示存在要在运行时激活的承载启动程序集。A HostingStartup attribute indicates the presence of a hosting startup assembly to activate at runtime.

将自动扫描输入程序集或包含 Startup 类的程序集以查找 HostingStartup 属性。The entry assembly or the assembly containing the Startup class is automatically scanned for the HostingStartup attribute. 用于搜索 HostingStartup 属性的程序集列表在运行时从 WebHostDefaults.HostingStartupAssembliesKey 中的配置加载。The list of assemblies to search for HostingStartup attributes is loaded at runtime from configuration in the WebHostDefaults.HostingStartupAssembliesKey. 要从发现中排除的程序集列表从 WebHostDefaults.HostingStartupExcludeAssembliesKey 加载。The list of assemblies to exclude from discovery is loaded from the WebHostDefaults.HostingStartupExcludeAssembliesKey. 有关详细信息,请参阅 Web 主机:承载启动程序集Web 主机:承载启动排除程序集For more information, see Web Host: Hosting Startup Assemblies and Web Host: Hosting Startup Exclude Assemblies.

在以下示例中,承载启动程序集的命名空间为 StartupEnhancementIn the following example, the namespace of the hosting startup assembly is StartupEnhancement. 包含承载启动代码的类是 StartupEnhancementHostingStartupThe class containing the hosting startup code is StartupEnhancementHostingStartup:

[assembly: HostingStartup(typeof(StartupEnhancement.StartupEnhancementHostingStartup))]

HostingStartup 属性通常位于承载启动程序集的 IHostingStartup 实现类文件中。The HostingStartup attribute is typically located in the hosting startup assembly's IHostingStartup implementation class file.

发现加载的承载启动程序集Discover loaded hosting startup assemblies

要发现加载的承载启动程序集,请启用日志记录并检查应用的日志。To discover loaded hosting startup assemblies, enable logging and check the app's logs. 记录加载程序集时发生的错误。Errors that occur when loading assemblies are logged. 会在调试级别记录加载的承载启动程序集,并记录所有错误。Loaded hosting startup assemblies are logged at the Debug level, and all errors are logged.

禁用承载启动程序集的自动加载Disable automatic loading of hosting startup assemblies

要禁用承载启动程序集的自动加载,请使用以下方法之一:To disable automatic loading of hosting startup assemblies, use one of the following approaches:

  • 要阻止加载所有承载启动程序集,请将以下内容之一设置为 true1To prevent all hosting startup assemblies from loading, set one of the following to true or 1:
  • 要阻止加载特定的承载启动程序集,请将以下之一设置为以分号分隔的承载启动程序集字符串,以便在启动时排除:To prevent specific hosting startup assemblies from loading, set one of the following to a semicolon-delimited string of hosting startup assemblies to exclude at startup:

如果同时设置了主机配置设置和环境变量,则主机设置将控制行为。If both the host configuration setting and the environment variable are set, the host setting controls the behavior.

如果使用主机设置或环境变量来禁用承载启动程序集,将全局禁用程序集,并可能会禁用应用的多个特征。Disabling hosting startup assemblies using the host setting or environment variable disables the assembly globally and may disable several characteristics of an app.

项目Project

使用以下任一项目类型创建承载启动:Create a hosting startup with either of the following project types:

类库Class library

可在类库中提供承载启动增强。A hosting startup enhancement can be provided in a class library. 库包含 HostingStartup 属性。The library contains a HostingStartup attribute.

示例代码包括 Razor Pages 应用、HostingStartupApp 和类库 HostingStartupLibrary。The sample code includes a Razor Pages app, HostingStartupApp, and a class library, HostingStartupLibrary. 类库:The class library:

  • 包含承载启动类 ServiceKeyInjection,用于实现 IHostingStartupContains a hosting startup class, ServiceKeyInjection, which implements IHostingStartup. ServiceKeyInjection 使用内存中配置提供程序 (AddInMemoryCollection) 将一对服务字符串添加到应用的配置中。ServiceKeyInjection adds a pair of service strings to the app's configuration using the in-memory configuration provider (AddInMemoryCollection).
  • 包含 HostingStartup 属性,用于标识承载启动的命名空间和类。Includes a HostingStartup attribute that identifies the hosting startup's namespace and class.

ServiceKeyInjection 类的 Configure 方法使用 IWebHostBuilder 将增强功能添加到应用。The ServiceKeyInjection class's Configure method uses an IWebHostBuilder to add enhancements to an app.

HostingStartupLibrary/ServiceKeyInjection.cs:HostingStartupLibrary/ServiceKeyInjection.cs:

[assembly: HostingStartup(typeof(HostingStartupLibrary.ServiceKeyInjection))]

namespace HostingStartupLibrary
{
    public class ServiceKeyInjection : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(config =>
            {
                var dict = new Dictionary<string, string>
                {
                    {"DevAccount_FromLibrary", "DEV_1111111-1111"},
                    {"ProdAccount_FromLibrary", "PROD_2222222-2222"}
                };

                config.AddInMemoryCollection(dict);
            });
        }
    }
}

应用的索引页读取并呈现类库承载启动程序集设置的两个键的配置值:The app's Index page reads and renders the configuration values for the two keys set by the class library's hosting startup assembly:

HostingStartupApp/Pages/Index.cshtml.cs:HostingStartupApp/Pages/Index.cshtml.cs:

public class IndexModel : PageModel
{
    public IndexModel(IConfiguration config)
    {
        ServiceKey_Development_Library = config["DevAccount_FromLibrary"];
        ServiceKey_Production_Library = config["ProdAccount_FromLibrary"];
        ServiceKey_Development_Package = config["DevAccount_FromPackage"];
        ServiceKey_Production_Package = config["ProdAccount_FromPackage"];
    }

    public string ServiceKey_Development_Library { get; private set; }
    public string ServiceKey_Production_Library { get; private set; }
    public string ServiceKey_Development_Package { get; private set; }
    public string ServiceKey_Production_Package { get; private set; }

    public void OnGet()
    {
    }
}

示例代码还包括一个 NuGet 包项目,该项目提供单独的承载启动 HostingStartupPackage。The sample code also includes a NuGet package project that provides a separate hosting startup, HostingStartupPackage. 该包具有与前述类库相同的特征。The package has the same characteristics of the class library described earlier. 包:The package:

  • 包含承载启动类 ServiceKeyInjection,用于实现 IHostingStartupContains a hosting startup class, ServiceKeyInjection, which implements IHostingStartup. ServiceKeyInjection 将一对服务字符串添加到应用的配置中。ServiceKeyInjection adds a pair of service strings to the app's configuration.
  • 包含 HostingStartup 属性。Includes a HostingStartup attribute.

HostingStartupPackage/ServiceKeyInjection.cs:HostingStartupPackage/ServiceKeyInjection.cs:

[assembly: HostingStartup(typeof(HostingStartupPackage.ServiceKeyInjection))]

namespace HostingStartupPackage
{
    public class ServiceKeyInjection : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration(config =>
            {
                var dict = new Dictionary<string, string>
                {
                    {"DevAccount_FromPackage", "DEV_3333333-3333"},
                    {"ProdAccount_FromPackage", "PROD_4444444-4444"}
                };

                config.AddInMemoryCollection(dict);
            });
        }
    }
}

应用的索引页读取并呈现包承载启动程序集设置的两个键的配置值:The app's Index page reads and renders the configuration values for the two keys set by the package's hosting startup assembly:

HostingStartupApp/Pages/Index.cshtml.cs:HostingStartupApp/Pages/Index.cshtml.cs:

public class IndexModel : PageModel
{
    public IndexModel(IConfiguration config)
    {
        ServiceKey_Development_Library = config["DevAccount_FromLibrary"];
        ServiceKey_Production_Library = config["ProdAccount_FromLibrary"];
        ServiceKey_Development_Package = config["DevAccount_FromPackage"];
        ServiceKey_Production_Package = config["ProdAccount_FromPackage"];
    }

    public string ServiceKey_Development_Library { get; private set; }
    public string ServiceKey_Production_Library { get; private set; }
    public string ServiceKey_Development_Package { get; private set; }
    public string ServiceKey_Production_Package { get; private set; }

    public void OnGet()
    {
    }
}

无入口点的控制台应用Console app without an entry point

此方法仅适用于 .NET Core 应用,不适用于 .NET Framework。This approach is only available for .NET Core apps, not .NET Framework.

可在包含 HostingStartup 属性的无入口点的控制台应用中提供动态承载启动增强功能,该功能无需编译时引用进行激活。A dynamic hosting startup enhancement that doesn't require a compile-time reference for activation can be provided in a console app without an entry point that contains a HostingStartup attribute. 发布控制台应用会生成可从运行时存储中使用的承载启动程序集。Publishing the console app produces a hosting startup assembly that can be consumed from the runtime store.

此过程中使用没有入口点的控制台应用,因为:A console app without an entry point is used in this process because:

  • 需要依赖项文件来使用承载启动程序集中的承载启动。A dependencies file is required to consume the hosting startup in the hosting startup assembly. 依赖项文件是一种可运行的应用资产,它通过发布应用而不是库来生成。A dependencies file is a runnable app asset that's produced by publishing an app, not a library.
  • 无法直接将库添加到运行时包存储,该过程需要一个以已共享运行时为目标的可运行项目。A library can't be added directly to the runtime package store, which requires a runnable project that targets the shared runtime.

创建动态承载启动过程中:In the creation of a dynamic hosting startup:

  • 从控制台应用创建承载启动程序集,无需以下入口点:A hosting startup assembly is created from the console app without an entry point that:
    • 包含 IHostingStartup 实现的类。Includes a class that contains the IHostingStartup implementation.
    • 包含用于识别 IHostingStartup 实现类的 HostingStartup 属性。Includes a HostingStartup attribute to identify the IHostingStartup implementation class.
  • 发布控制台应用,获取承载启动的依赖项。The console app is published to obtain the hosting startup's dependencies. 发布控制台应用的结果是从依赖项文件中删除了未使用的依赖项。A consequence of publishing the console app is that unused dependencies are trimmed from the dependencies file.
  • 修改依赖项文件以设置承载启动程序集的运行时位置。The dependencies file is modified to set the runtime location of the hosting startup assembly.
  • 承载启动程序集及其依赖项文件位于运行时包存储中。The hosting startup assembly and its dependencies file is placed into the runtime package store. 要发现承载启动程序集及其依赖项文件,它们将在一对环境变量中列出。To discover the hosting startup assembly and its dependencies file, they're listed in a pair of environment variables.

控制台应用引用 Microsoft.AspNetCore.Hosting.Abstractions 包:The console app references the Microsoft.AspNetCore.Hosting.Abstractions package:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" 
                      Version="2.1.1" />
  </ItemGroup>

</Project>

生成 IWebHost 时,HostingStartup 属性将类标识为 IHostingStartup 的实现,用于加载和执行。A HostingStartup attribute identifies a class as an implementation of IHostingStartup for loading and execution when building the IWebHost. 在下面的示例中,命名空间为 StartupEnhancement,类为 StartupEnhancementHostingStartupIn the following example, the namespace is StartupEnhancement, and the class is StartupEnhancementHostingStartup:

[assembly: HostingStartup(typeof(StartupEnhancement.StartupEnhancementHostingStartup))]

类实现 IHostingStartupA class implements IHostingStartup. 类的 Configure 方法使用 IWebHostBuilder 将增强功能添加到应用。The class's Configure method uses an IWebHostBuilder to add enhancements to an app. 用户代码中 Startup.Configure 之前的运行时调用托管启动程序集中的 IHostingStartup.Configure,允许用户代码覆盖托管启动程序集提供的任何配置。IHostingStartup.Configure in the hosting startup assembly is called by the runtime before Startup.Configure in user code, which allows user code to overwrite any configuration provided by the hosting startup assembly.

namespace StartupEnhancement
{
    public class StartupEnhancementHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            // Use the IWebHostBuilder to add app enhancements.
        }
    }
}

生成 IHostingStartup 项目时,依赖项文件 (*.deps.json) 将程序集的 runtime 位置设为 bin 文件夹:When building an IHostingStartup project, the dependencies file (*.deps.json) sets the runtime location of the assembly to the bin folder:

"targets": {
  ".NETCoreApp,Version=v2.1": {
    "StartupEnhancement/1.0.0": {
      "dependencies": {
        "Microsoft.AspNetCore.Hosting.Abstractions": "2.1.1"
      },
      "runtime": {
        "StartupEnhancement.dll": {}
      }
    }
  }
}

仅显示部分文件。Only part of the file is shown. 示例中程序集的名称是 StartupEnhancementThe assembly name in the example is StartupEnhancement.

托管启动提供的配置Configuration provided by the hosting startup

处理配置有两种方法,具体取决于是希望托管启动的配置优先还是应用的配置优先:There are two approaches to handling configuration depending on whether you want the hosting startup's configuration to take precedence or the app's configuration to take precedence:

  1. 使用 ConfigureAppConfiguration 为应用提供配置,在应用的 ConfigureAppConfiguration 委托执行后加载配置。Provide configuration to the app using ConfigureAppConfiguration to load the configuration after the app's ConfigureAppConfiguration delegates execute. 使用此方法,托管启动配置优先于应用的配置。Hosting startup configuration takes priority over the app's configuration using this approach.
  2. 使用 UseConfiguration 为应用提供配置,在应用的 ConfigureAppConfiguration 委托执行之前加载配置。Provide configuration to the app using UseConfiguration to load the configuration before the app's ConfigureAppConfiguration delegates execute. 使用此方法,应用的配置值优先于托管启动程序提供的值。The app's configuration values take priority over those provided by the hosting startup using this approach.
public class ConfigurationInjection : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {
        Dictionary<string, string> dict;

        builder.ConfigureAppConfiguration(config =>
        {
            dict = new Dictionary<string, string>
            {
                {"ConfigurationKey1", 
                    "From IHostingStartup: Higher priority than the app's configuration."},
            };

            config.AddInMemoryCollection(dict);
        });

        dict = new Dictionary<string, string>
        {
            {"ConfigurationKey2", 
                "From IHostingStartup: Lower priority than the app's configuration."},
        };

        var builtConfig = new ConfigurationBuilder()
            .AddInMemoryCollection(dict)
            .Build();

        builder.UseConfiguration(builtConfig);
    }
}

指定承载启动程序集Specify the hosting startup assembly

对于类库或控制台应用提供的承载启动,请在 ASPNETCORE_HOSTINGSTARTUPASSEMBLIES 环境变量中指定承载启动程序集的名称。For either a class library- or console app-supplied hosting startup, specify the hosting startup assembly's name in the ASPNETCORE_HOSTINGSTARTUPASSEMBLIES environment variable. 环境变量是以分号分隔的程序集列表。The environment variable is a semicolon-delimited list of assemblies.

仅扫描承载启动程序集以查找 HostingStartup 属性。Only hosting startup assemblies are scanned for the HostingStartup attribute. 对于示例应用 HostingStartupApp,要发现前述的承载启动,请将环境变量设置为以下值:For the sample app, HostingStartupApp, to discover the hosting startups described earlier, the environment variable is set to the following value:

HostingStartupLibrary;HostingStartupPackage;StartupDiagnostics

还可使用承载启动程序集主机配置设置来设置此承载启动程序集。A hosting startup assembly can also be set using the Hosting Startup Assemblies host configuration setting.

存在多个托管启动程序集时,将按列出程序集的顺序执行 Configure 方法。When multiple hosting startup assembles are present, their Configure methods are executed in the order that the assemblies are listed.

激活Activation

承载启动激活的选项包括:Options for hosting startup activation are:

  • 运行时存储 – 激活无需用于激活的编译时引用。Runtime store – Activation doesn't require a compile-time reference for activation. 示例应用将承载启动程序集和依赖项文件放入文件夹“deployment”,以便在多计算机环境中部署承载启动。The sample app places the hosting startup assembly and dependencies files into a folder, deployment, to facilitate deployment of the hosting startup in a multimachine environment. “deployment”文件夹还包括 PowerShell 脚本,该脚本可在部署系统上创建或修改环境变量以启用承载启动。The deployment folder also includes a PowerShell script that creates or modifies environment variables on the deployment system to enable the hosting startup.
  • 激活所需的编译时引用Compile-time reference required for activation

运行时存储Runtime store

承载启动实现位于运行时存储中。The hosting startup implementation is placed in the runtime store. 增强型应用无需对程序集进行编译时引用。A compile-time reference to the assembly isn't required by the enhanced app.

构建承载启动后,使用清单项目文件和 dotnet store 命令生成运行时存储。After the hosting startup is built, a runtime store is generated using the manifest project file and the dotnet store command.

dotnet store --manifest {MANIFEST FILE} --runtime {RUNTIME IDENTIFIER} --output {OUTPUT LOCATION} --skip-optimization

在示例应用(RuntimeStore 项目)中,使用以下命令:In the sample app (RuntimeStore project) the following command is used:

dotnet store --manifest store.manifest.csproj --runtime win7-x64 --output ./deployment/store --skip-optimization

对于发现运行时存储的运行时,运行时存储的位置将添加到 DOTNET_SHARED_STORE 环境变量中。For the runtime to discover the runtime store, the runtime store's location is added to the DOTNET_SHARED_STORE environment variable.

修改并放置承载启动的依赖项文件Modify and place the hosting startup's dependencies file

要在未包引用增强功能的情况下激活增强功能,请使用 additionalDeps 为运行时指定附加依赖项。To activate the enhancement without a package reference to the enhancement, specify additional dependencies to the runtime with additionalDeps. 使用 additionalDeps,你可以:additionalDeps allows you to:

  • 通过提供一组附加的 *.deps.json 文件来扩展应用的库图,以便在启动时与应用自身的 *.deps.json 文件合并。Extend the app's library graph by providing a set of additional *.deps.json files to merge with the app's own *.deps.json file on startup.
  • 使承载启动程序集可被发现并可加载。Make the hosting startup assembly discoverable and loadable.

生成附加依赖项文件的推荐方法是:The recommended approach for generating the additional dependencies file is to:

  1. 对上一节中引用的运行时存储清单文件执行 dotnet publishExecute dotnet publish on the runtime store manifest file referenced in the previous section.
  2. 从库中删除清单引用,以及生成的 *deps.json 文件的 runtime 部分。Remove the manifest reference from libraries and the runtime section of the resulting *deps.json file.

在示例项目中,store.manifest/1.0.0 属性已从 targetslibraries 部分中删除:In the example project, the store.manifest/1.0.0 property is removed from the targets and libraries section:

{
  "runtimeTarget": {
    "name": ".NETCoreApp,Version=v2.1",
    "signature": "4ea77c7b75ad1895ae1ea65e6ba2399010514f99"
  },
  "compilationOptions": {},
  "targets": {
    ".NETCoreApp,Version=v2.1": {
      "store.manifest/1.0.0": {
        "dependencies": {
          "StartupDiagnostics": "1.0.0"
        },
        "runtime": {
          "store.manifest.dll": {}
        }
      },
      "StartupDiagnostics/1.0.0": {
        "runtime": {
          "lib/netcoreapp2.1/StartupDiagnostics.dll": {
            "assemblyVersion": "1.0.0.0",
            "fileVersion": "1.0.0.0"
          }
        }
      }
    }
  },
  "libraries": {
    "store.manifest/1.0.0": {
      "type": "project",
      "serviceable": false,
      "sha512": ""
    },
    "StartupDiagnostics/1.0.0": {
      "type": "package",
      "serviceable": true,
      "sha512": "sha512-oiQr60vBQW7+nBTmgKLSldj06WNLRTdhOZpAdEbCuapoZ+M2DJH2uQbRLvFT8EGAAv4TAKzNtcztpx5YOgBXQQ==",
      "path": "startupdiagnostics/1.0.0",
      "hashPath": "startupdiagnostics.1.0.0.nupkg.sha512"
    }
  }
}

*.deps.json 文件放入以下位置:Place the *.deps.json file into the following location:

{ADDITIONAL DEPENDENCIES PATH}/shared/{SHARED FRAMEWORK NAME}/{SHARED FRAMEWORK VERSION}/{ENHANCEMENT ASSEMBLY NAME}.deps.json
  • {ADDITIONAL DEPENDENCIES PATH} – 添加到 DOTNET_ADDITIONAL_DEPS 环境变量中的位置。{ADDITIONAL DEPENDENCIES PATH} – Location added to the DOTNET_ADDITIONAL_DEPS environment variable.
  • {SHARED FRAMEWORK NAME} – 此附加依赖项文件所需的共享框架。{SHARED FRAMEWORK NAME} – Shared framework required for this additional dependencies file.
  • {SHARED FRAMEWORK VERSION} – 最小共享框架版本。{SHARED FRAMEWORK VERSION} – Minimum shared framework version.
  • {ENHANCEMENT ASSEMBLY NAME} – 增强功能的程序集名称。{ENHANCEMENT ASSEMBLY NAME} – The enhancement's assembly name.

在示例应用(RuntimeStore 项目)中,附加依赖项文件放于以下位置:In the sample app (RuntimeStore project), the additional dependencies file is placed into the following location:

additionalDeps/shared/Microsoft.AspNetCore.App/2.1.0/StartupDiagnostics.deps.json

对于发现运行时存储位置的运行时,附加依赖项文件位置将添加到 DOTNET_ADDITIONAL_DEPS 环境变量中。For runtime to discover the runtime store location, the additional dependencies file location is added to the DOTNET_ADDITIONAL_DEPS environment variable.

在示例应用(RuntimeStore 项目)中,使用 PowerShell 脚本完成构建运行时存储并生成附加依赖项文件。In the sample app (RuntimeStore project), building the runtime store and generating the additional dependencies file is accomplished using a PowerShell script.

有关如何设置各种操作系统的环境变量的示例,请参阅使用多个环境For examples of how to set environment variables for various operating systems, see Use multiple environments.

部署Deployment

为了便于在多计算机环境中部署托承载启动,示例应用在已发布的输出中创建一个“deployment”文件夹,其中包含:To facilitate the deployment of a hosting startup in a multimachine environment, the sample app creates a deployment folder in published output that contains:

  • 承载启动运行时存储。The hosting startup runtime store.
  • 承载启动依赖项文件。The hosting startup dependencies file.
  • PowerShell 脚本,用于创建或修改 ASPNETCORE_HOSTINGSTARTUPASSEMBLIESDOTNET_SHARED_STOREDOTNET_ADDITIONAL_DEPS 以支持激活承载启动。A PowerShell script that creates or modifies the ASPNETCORE_HOSTINGSTARTUPASSEMBLIES, DOTNET_SHARED_STORE, and DOTNET_ADDITIONAL_DEPS to support the activation of the hosting startup. 从部署系统上的管理 PowerShell 命令提示符运行脚本。Run the script from an administrative PowerShell command prompt on the deployment system.

NuGet 程序包NuGet package

可在 NuGet 包中提供承载启动增强。A hosting startup enhancement can be provided in a NuGet package. 该包含有 HostingStartup 属性。The package has a HostingStartup attribute. 包提供的承载启动类型使用以下任一方法提供给应用:The hosting startup types provided by the package are made available to the app using either of the following approaches:

  • 增强型应用的项目文件在应用的项目文件(编译时引用)中为承载启动提供了包引用。The enhanced app's project file makes a package reference for the hosting startup in the app's project file (a compile-time reference). 有了编译时引用,承载启动程序集及其所有依赖项都会合并到应用的依赖项文件 (*.deps.json) 中。With the compile-time reference in place, the hosting startup assembly and all of its dependencies are incorporated into the app's dependency file (*.deps.json). 此方法适用于已发布到 nuget.org 的承载启动程序集包。This approach applies to a hosting startup assembly package published to nuget.org.
  • 承载启动的依赖项文件可用于增强型应用,如运行时存储部分所述(无编译时引用)。The hosting startup's dependencies file is made available to the enhanced app as described in the Runtime store section (without a compile-time reference).

有关 NuGet 包和运行时存储的详细信息,请参阅以下主题:For more information on NuGet packages and the runtime store, see the following topics:

项目 bin 文件夹Project bin folder

承载启动增强功能可通过增强型应用中的 bin -deployed 程序集提供。A hosting startup enhancement can be provided by a bin-deployed assembly in the enhanced app. 程序集提供的承载启动类型使用以下任一方法提供给应用:The hosting startup types provided by the assembly are made available to the app using either of the following approaches:

  • 增强型应用的项目文件对承载启动进行了程序集引用(编译时引用)。The enhanced app's project file makes an assembly reference to the hosting startup (a compile-time reference). 有了编译时引用,承载启动程序集及其所有依赖项都会合并到应用的依赖项文件 (*.deps.json) 中。With the compile-time reference in place, the hosting startup assembly and all of its dependencies are incorporated into the app's dependency file (*.deps.json). 如果部署方案要求将已编译承载启动库的程序集(DLL 文件)移动到使用项目中或使用项目可访问的位置,并且对承载启动程序集进行编译时引用,此方法适用。This approach applies when the deployment scenario calls for moving the compiled hosting startup library's assembly (DLL file) to the consuming project or to a location accessible by the consuming project and a compile-time reference is made to the hosting startup's assembly.
  • 承载启动的依赖项文件可用于增强型应用,如运行时存储部分所述(无编译时引用)。The hosting startup's dependencies file is made available to the enhanced app as described in the Runtime store section (without a compile-time reference).

示例代码Sample code

示例代码如何下载)演示了承载启动实现方案:The sample code (how to download) demonstrates hosting startup implementation scenarios:

  • 两个承载启动程序集(类库)分别设置一对内存中配置键值对:Two hosting startup assemblies (class libraries) set a pair of in-memory configuration key-value pairs each:
    • NuGet 包 (HostingStartupPackage)NuGet package (HostingStartupPackage)
    • 类库 (HostingStartupLibrary)Class library (HostingStartupLibrary)
  • 从运行时存储部署的程序集 (StartupDiagnostics) 激活承载启动。A hosting startup is activated from a runtime store-deployed assembly (StartupDiagnostics). 该程序集在启动时将两个中间件添加到应用,用于提供以下内容的诊断信息:The assembly adds two middlewares to the app at startup that provide diagnostic information on:
    • 已注册服务Registered services
    • 地址(方案、主机、基路径、路径、查询字符串)Address (scheme, host, path base, path, query string)
    • 连接(远程 IP、远程端口、本地 IP、本地端口、客户端证书)Connection (remote IP, remote port, local IP, local port, client certificate)
    • 请求标头Request headers
    • 环境变量Environment variables

运行示例:To run the sample:

从 NuGet 包激活Activation from a NuGet package

  1. 使用 dotnet pack 命令编译 HostingStartupPackage 包。Compile the HostingStartupPackage package with the dotnet pack command.

  2. 将包的程序集名称 HostingStartupPackage 添加到 ASPNETCORE_HOSTINGSTARTUPASSEMBLIES 环境变量中。Add the package's assembly name of the HostingStartupPackage to the ASPNETCORE_HOSTINGSTARTUPASSEMBLIES environment variable.

  3. 编译并运行应用。Compile and run the app. 增强型应用中存在包引用(编译时引用)。A package reference is present in the enhanced app (a compile-time reference). 应用项目文件中的 <PropertyGroup> 指定包项目的输出 (../HostingStartupPackage/bin/Debug) 作为包源。A <PropertyGroup> in the app's project file specifies the package project's output (../HostingStartupPackage/bin/Debug) as a package source. 这允许应用使用该包而无需将包上传到 nuget.org。有关详细信息,请参阅 HostingStartupApp 项目文件中的说明。This allows the app to use the package without uploading the package to nuget.org. For more information, see the notes in the HostingStartupApp's project file.

    <PropertyGroup>
      <RestoreSources>$(RestoreSources);https://api.nuget.org/v3/index.json;../HostingStartupPackage/bin/Debug</RestoreSources>
    </PropertyGroup>
    
  4. 观察到索引页呈现的服务配置键值与包的 ServiceKeyInjection.Configure 方法设置的值匹配。Observe that the service configuration key values rendered by the Index page match the values set by the package's ServiceKeyInjection.Configure method.

如果更改并重新编译 HostingStartupPackage 项目,请清除本地 NuGet 包缓存,确保 HostingStartupApp 从本地缓存中收到更新后的包而不是旧包。If you make changes to the HostingStartupPackage project and recompile it, clear the local NuGet package caches to ensure that the HostingStartupApp receives the updated package and not a stale package from the local cache. 要清除本地 NuGet 缓存,请执行以下 dotnet nuget locals 命令:To clear the local NuGet caches, execute the following dotnet nuget locals command:

dotnet nuget locals all --clear

从类库激活Activation from a class library

  1. 使用 dotnet build 命令编译 HostingStartupLibrary 类库。Compile the HostingStartupLibrary class library with the dotnet build command.

  2. 将类库的程序集名称 HostingStartupLibrary 添加到 ASPNETCORE_HOSTINGSTARTUPASSEMBLIES 环境变量中。Add the class library's assembly name of HostingStartupLibrary to the ASPNETCORE_HOSTINGSTARTUPASSEMBLIES environment variable.

  3. bin - 通过将类库编译输出中的 HostingStartupLibrary.dll 文件复制到应用的 bin/Debug 文件夹,将类库程序集部署到应用。bin-deploy the class library's assembly to the app by copying the HostingStartupLibrary.dll file from the class library's compiled output to the app's bin/Debug folder.

  4. 编译并运行应用。Compile and run the app. 应用项目文件中的 <ItemGroup> 引用类库的程序集 (.\bin\Debug\netcoreapp2.1\HostingStartupLibrary.dll)(编译时引用)。An <ItemGroup> in the app's project file references the class library's assembly (.\bin\Debug\netcoreapp2.1\HostingStartupLibrary.dll) (a compile-time reference). 有关详细信息,请参阅 HostingStartupApp 项目文件中的说明。For more information, see the notes in the HostingStartupApp's project file.

    <ItemGroup>
      <Reference Include=".\bin\Debug\netcoreapp2.1\HostingStartupLibrary.dll">
        <HintPath>.\bin\Debug\netcoreapp2.1\HostingStartupLibrary.dll</HintPath>
        <SpecificVersion>False</SpecificVersion>
      </Reference>
    </ItemGroup>
    
  5. 观察到索引页呈现的服务配置键值与类库的 ServiceKeyInjection.Configure 方法设置的值匹配。Observe that the service configuration key values rendered by the Index page match the values set by the class library's ServiceKeyInjection.Configure method.

从运行时存储部署的程序集激活Activation from a runtime store-deployed assembly

  1. StartupDiagnostics 项目使用 PowerShell 修改其 StartupDiagnostics.deps.json 文件。The StartupDiagnostics project uses PowerShell to modify its StartupDiagnostics.deps.json file. 默认情况下,Windows 7 SP1 和 Windows Server 2008 R2 SP1 及以后版本的 Windows 上安装有 PowerShell。PowerShell is installed by default on Windows starting with Windows 7 SP1 and Windows Server 2008 R2 SP1. 若要在其他平台上获取 PowerShell,请参阅安装 Windows PowerShellTo obtain PowerShell on other platforms, see Installing Windows PowerShell.
  2. 执行 RuntimeStore文件夹中的 build.ps1 脚本。Execute the build.ps1 script in the RuntimeStore folder. 脚本:The script:
    • 生成 StartupDiagnostics 包。Generates the StartupDiagnostics package.
    • 在 store 文件夹中生成 StartupDiagnostics 的运行时存储。Generates the runtime store for StartupDiagnostics in the store folder. 该脚本中的 dotnet store 命令使用 win7-x64 运行时标识符 (RID) 将托管启动部署到 Windows。The dotnet store command in the script uses the win7-x64 runtime identifier (RID) for a hosting startup deployed to Windows. 为其他运行时提供托管启动程序集时,在脚本第 37 行上替换为正确的 RID。When providing the hosting startup for a different runtime, substitute the correct RID on line 37 of the script.
    • 在 additionalDeps/shared/Microsoft.AspNetCore.App/{共享框架版本}/ 文件夹中生成 StartupDiagnosticsadditionalDepsGenerates the additionalDeps for StartupDiagnostics in the additionalDeps/shared/Microsoft.AspNetCore.App/{Shared Framework Version}/ folder.
    • 将 deploy.ps1 文件放置在 deployment 文件夹中。Places the deploy.ps1 file in the deployment folder.
  3. 运行 deployment 文件夹中的 deploy.ps1 脚本。Run the deploy.ps1 script in the deployment folder. 脚本将:The script appends:
    • StartupDiagnostics 追加到 ASPNETCORE_HOSTINGSTARTUPASSEMBLIES 环境变量。StartupDiagnostics to the ASPNETCORE_HOSTINGSTARTUPASSEMBLIES environment variable.
    • 托管启动程序集依赖项路径追加到 DOTNET_ADDITIONAL_DEPS 环境变量。The hosting startup dependencies path to the DOTNET_ADDITIONAL_DEPS environment variable.
    • 运行时存储路径追加到 DOTNET_SHARED_STORE 环境变量。The runtime store path to the DOTNET_SHARED_STORE environment variable.
  4. 运行示例应用。Run the sample app.
  5. 请求 /services 终结点以查看应用的注册服务。Request the /services endpoint to see the app's registered services. 请求 /diag 终结点以查看诊断信息。Request the /diag endpoint to see the diagnostic information.