如何在 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 应用程序