Search code examples
c#azure-service-fabric

Shared function to get configuration parameter for console, web app and Service Fabric microservice


I want to have a shared function that returns the application setting of a parameter:

public static string GetAppSettings(string key)
{
  string sfAppName = Environment.GetEnvironmentVariable("Fabric_ApplicationName");
     if (string.IsNullOrEmpty(sfAppName)) // we are NOT in SF 
     {
         return ConfigurationManager.AppSettings[key];
     }
     else
     {
         ConfigurationPackage configurationPackage = FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config");
         return configurationPackage.Settings.Sections["appSettings"].Parameters[key].Value;
      }
}

So that this function gets the parameter from appSettings.config if the calling code is running in a standard web app, and from Local.1Node.xml if the calling code is running as a Service Fabric microservice.

When I put this function outside of the MicroServices "folder" (in the Shared project) I can't import

using System.Fabric;

Is there a way a way to do this? And is it a good practice?


Solution

  • Sure you can, in your shared project, add a reference to the Microsoft.ServiceFabric Nuget package.

    Install-Package Microsoft.ServiceFabric or dotnet add package Microsoft.ServiceFabric