How to parameterize configuration files in Service Fabric
This article shows you how to parameterize a configuration file in Service Fabric. If you're not already familiar with the core concepts of managing applications for multiple environments, read Manage applications for multiple environments.
Procedure for parameterizing configuration files
In this example, you override a configuration value using parameters in your application deployment.
Open the <MyService>\PackageRoot\Config\Settings.xml file in your service project.
Set a configuration parameter name and value, for example cache size equal to 25, by adding the following XML:
<Section Name="MyConfigSection"> <Parameter Name="CacheSize" Value="25" /> </Section>
Save and close the file.
Open the <MyApplication>\ApplicationPackageRoot\ApplicationManifest.xml file.
In the ApplicationManifest.xml file, declare a parameter and default value in the
Parameters
element. It's recommended that the parameter name contains the name of the service (for example, "MyService").<Parameters> <Parameter Name="MyService_CacheSize" DefaultValue="80" /> </Parameters>
In the
ServiceManifestImport
section of the ApplicationManifest.xml file, add aConfigOverrides
andConfigOverride
element, referencing the configuration package, the section, and the parameter.<ConfigOverrides> <ConfigOverride Name="Config"> <Settings> <Section Name="MyConfigSection"> <Parameter Name="CacheSize" Value="[MyService_CacheSize]" /> </Section> </Settings> </ConfigOverride> </ConfigOverrides>
Note
In the case where you add a ConfigOverride, Service Fabric always chooses the application parameters or the default value specified in the application manifest.
Access parameterized configurations in code
You can access the configuration in your settings.xml file programmatically. Take for example, the following configuration XML file:
<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>
Use the following code to access the parameters:
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);
}
Here Parameter.Name
will be MyParameter and Parameter.Value
will be Value1
Next steps
For information about other app management capabilities that are available in Visual Studio, see Manage your Service Fabric applications in Visual Studio.