在 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 和類別庫 HostingStartupLibraryThe 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.csHostingStartupLibrary/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.csHostingStartupApp/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()
    {
    }
}

程式碼範例也包含提供另一個主機啟動 (HostingStartupPackage) 的 NuGet 套件專案。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.csHostingStartupPackage/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.csHostingStartupApp/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.
    • 包括 HostingStartup 屬性以識別 IHostingStartup 實作類別。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. 執行階段會先呼叫裝載啟動組件中的 IHostingStartup.Configure,再呼叫使用者程式碼中的 Startup.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. 在應用程式的 ConfigureAppConfiguration 委派執行之前使用 UseConfiguration 載入設定,以提供設定給應用程式。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.
  • 建立或修改 ASPNETCORE_HOSTINGSTARTUPASSEMBLIESDOTNET_SHARED_STOREDOTNET_ADDITIONAL_DEPS 以支援啟用裝載啟動的 PowerShell 指令碼。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 下的組件可提供裝載啟動增強功能。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 one 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 making a compile-time reference to the hosting startup's assembly (.dll file) and moving the assembly to either:
    • 取用專案。The consuming project.
    • 取用專案可存取的位置。A location accessible by the consuming project.
  • 裝載啟動的相依性檔案可提供增強應用程式使用,如執行階段存放區 區段 (沒有編譯時間參考)。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).
  • 以 .NET Framework 為目標時,可在預設載入內容中載入組件,在 .NET Framework 上,這表示組件位於下列其中一個位置:When targeting the .NET Framework, the assembly is loadable in the default load context, which on .NET Framework means that the assembly is located at either of the following locations:
    • 應用程式基底路徑 – 應用程式可執行檔 ( .exe) 所在的 bin 資料夾。Application base path – The bin folder where the app's executable (.exe) is located.
    • 全域組件快取 (GAC) – GAC 會儲存數個 .NET Framework 應用程式共用的組件。Global Assembly Cache (GAC) – The GAC stores assemblies that several .NET Framework apps share. 如需詳細資訊,請參閱如何:將組件安裝到全域組件快取 (位於 .NET Framework 文件)。For more information, see How to: Install an assembly into the global assembly cache in the .NET Framework documentation.

範例程式碼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. HostingStartupLibrary.dll 檔案從類別庫的編譯輸出複製到應用程式的 bin/Debug 資料夾,在應用程式的 bin 下部署類別庫組件。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-x64runtime identifier (RID) (執行階段識別碼 (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:
    • StartupDiagnosticsASPNETCORE_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.