如何在 Service Fabric 中將組態檔參數化

本文會示範如何參數化 Service Fabric 中的設定檔。 如果您尚未熟悉管理多個環境之應用程式的核心概念,請參閱管理多個環境的應用程式

參數化設定檔的程序

在此範例中,您會使用應用程式部署中的參數來覆寫設定值。

  1. 開啟服務專案中的 <MyService>\PackageRoot\Config\Settings.xml 檔案。

  2. 新增下列 XML 來設定組態參數名稱和值 (例如快取大小等於 25):

     <Section Name="MyConfigSection">
       <Parameter Name="CacheSize" Value="25" />
     </Section>
    
  3. 儲存並關閉檔案。

  4. 開啟 <MyApplication>\ApplicationPackageRoot\ApplicationManifest.xml 檔案。

  5. 在 ApplicationManifest.xml 檔案中,於 Parameters 元素中宣告參數和預設值。 建議使參數名稱包含服務的名稱 (例如 "MyService")。

     <Parameters>
       <Parameter Name="MyService_CacheSize" DefaultValue="80" />
     </Parameters>
    
  6. 在 ApplicationManifest.xml 檔案的 ServiceManifestImport 區段中新增 ConfigOverridesConfigOverride 元素,並參考設定套件、區段和參數。

     <ConfigOverrides>
       <ConfigOverride Name="Config">
           <Settings>
             <Section Name="MyConfigSection">
                 <Parameter Name="CacheSize" Value="[MyService_CacheSize]" />
             </Section>
           </Settings>
       </ConfigOverride>
     </ConfigOverrides>
    

注意

在您新增 ConfigOverride 的情況下,Service Fabric 一律會選擇應用程式資訊清單中所指定的應用程式參數或預設值。

存取程式碼中的參數化設定

您可以透過程式設計方式存取您 settings.xml 檔案中的設定。 例如:下列設定 XML 檔案:

<Settings
	xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://schemas.microsoft.com/2011/01/fabric">
	<!-- Add your custom configuration sections and parameters here -->
	<Section Name="MyConfigSection">
		<Parameter Name="MyParameter" Value="Value1" />
	</Section>
</Settings>     

使用下列程式碼來存取參數:

CodePackageActivationContext context = FabricRuntime.GetActivationContext();
var configSettings = context.GetConfigurationPackageObject("Config").Settings;
var data = configSettings.Sections["MyConfigSection"];
foreach (var parameter in data.Parameters)
{
  ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0} - {1}", parameter.Name, parameter.Value);
}

以下 Parameter.Name 將會是 MyParameter,而 Parameter.Value 將會是 Value1

下一步

如需 Visual Studio 中其他可用的應用程式管理功能的相關資訊,請參閱 在 Visual Studio 中管理 Service Fabric 應用程式