DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Working With dotConnect for Oracle in ASP.NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses

Trending

  • Stop Debugging Glue Jobs Manually: Building an Agentic Observability Layer for Data Pipelines
  • Why Your Test Automation Is Always Behind the Code And the Architecture That Fixes It
  • 5 Common Security Pitfalls in Serverless Architectures
  • Build a GitHub Slack Bot With AWS Bedrock and MCP, Part 1
  1. DZone
  2. Data Engineering
  3. Data
  4. Share ASP.NET Core appsettings.json With Service Fabric Microservices

Share ASP.NET Core appsettings.json With Service Fabric Microservices

How to store and consolidate configuration variables while also being able to deploy individual microservices.

By 
Andrej Medic user avatar
Andrej Medic
·
Jul. 22, 16 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
10.2K Views

Join the DZone community and get the full member experience.

Join For Free

If you’ve been working with Service Fabric, you have most likely come across the need to store configuration variables somewhere. This usually means defining and overriding parameters in the following files across various projects:

>ApplicationPackageRoot\ApplicationManifest.xml
ApplicationParameters\Local.xml
PackageRoot\Config\Settings.xml

As all my microservice and library projects have been converted over to the new .Net Core xproj structure, I wanted to consolidate and share the same settings .json files used in my .Net Core Web project across the entire solution whilst still maintaining the ability to deploy/publish individual microsevices. Taking inspiration from how this is achieved in .Net Core and as I’m targeting .Net Core RC2, I created the following appsettings.json files in my Web project, corresponding to the ASPNETCORE_ENVIRONMENT variable:

appsettings.json
appsettings.Development.json
appsettings.Staging.json
appsettings.Production.json

Example Web project appsettings.Development.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": ""
  }
}


For completeness, the Web project.json file should also define a custom publishOptions:

"publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.Development.json",
      "appsettings.Staging.json",
      "appsettings.Production.json",
      "web.config"
    ]
},


Next we need to create either a common .Net Core library project or within each microservice project add the following class:

using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.Extensions.Configuration;
using System;

namespace Acme.Helpers
{
    public static class ConfigurationHelper
    {
        public static ApplicationOptions GetConfiguration()
        {
            var appSettings = new AppSettings();
            var configRoot = GetConfigurationRoot();
            configRoot.Bind(appSettings);

            return result;
        }

        public static IConfigurationRoot GetConfigurationRoot()
        {
            IConfigurationRoot configuration = null;

            var basePath = PlatformServices.Default.Application.ApplicationBasePath;
            var environmentName = Environment.GetEnvironmentVariable(Acme.ASPNETCORE_ENVIRONMENT);

            if (!string.IsNullOrEmpty(environmentName))
            {
                var configurationBuilder = new ConfigurationBuilder()
                    .SetBasePath(basePath)
                    .AddJsonFile($"appsettings.{environmentName}.json");

                configuration = configurationBuilder.Build();
            }

            return configuration;
        }
    }
}

Note: The value of Acme.ASPNETCORE_ENVIRONMENT is "ASPNETCORE_ENVIRONMENT". Make sure ASPNETCORE_ENVIRONMENT is set on your target environment accordingly. Moreover the AppSettings class definition must correspond to the content of your appsettings.json file, as otherwise the configRoot.Bind(appSettings) will fail.

In each microservice project.json we’ll also need to add custom postcompile and postpublish scripts, with the complete file looking something like this:

{
  "title": "Acme.Service.Clock",
  "description": "Acme.Service.Clock",
  "version": "1.0.0-*",

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true,
    "compile": {
      "exclude": [
        "PackageRoot"
      ]
    } 
  },

  "dependencies": {
    "Microsoft.ServiceFabric": "5.1.150",
    "Microsoft.ServiceFabric.Actors": "2.1.150",
    "Microsoft.ServiceFabric.Data": "2.1.150",
    "Microsoft.ServiceFabric.Services": "2.1.150",
    "Microsoft.Framework.Configuration": "1.0.0-beta8",
    "Microsoft.Framework.Configuration.Json": "1.0.0-beta8",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Binder": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final"
  },

  "scripts": {
    "postcompile": [
      "xcopy /Y ..\\Web\\appsettings.Development.json %compile:OutputDir%\\win7-x64\\appsettings.Development.json*",
      "xcopy /Y ..\\Web\\appsettings.Staging.json %compile:OutputDir%\\win7-x64\\appsettings.Staging.json*",
      "xcopy /Y ..\\Web\\appsettings.Production.json %compile:OutputDir%\\win7-x64\\appsettings.Production.json*"
    ],
    "postpublish": [
      "xcopy /Y ..\\Web\\appsettings.Development.json %publish:OutputPath%",
      "xcopy /Y ..\\Web\\appsettings.Staging.json %publish:OutputPath%",
      "xcopy /Y ..\\Web\\appsettings.Production.json %publish:OutputPath%"
    ]
  },

  "frameworks": {
    "net46": { }
  },

  "runtimes": {
    "win7-x64": { }
  }

}

Note: For the scripts to work, adjust the location of the appsettings.json files to be relative to your solution and project structure.

With the above changes in place, whenever you now compile your microservice projects or deploy/publish them to a Service Fabric cluster, the corresponding appsettings.json files will also be copied, packaged and deployed! Moreover access to configuration variables within the appsettings.json file is achieved through the same low friction and strongly typed/bound mechanism as used in Asp.Net Core projects. The code would look something like:

var configuration = ConfigurationHelper.GetConfiguration();

if (configuration != null)
{
var instrumentationKey = configuration.ApplicationInsights.InstrumentationKey;
}

A final word, for production scenarios it is recommended that the content of appsettings.json be encrypted, in addition to the above ConfigurationHelper code being extended to support reloadOnChange events. Maybe a topic for future posts…

microservice ASP.NET Core ASP.NET Web Service .NET

Opinions expressed by DZone contributors are their own.

Related

  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Working With dotConnect for Oracle in ASP.NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook