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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  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.

Andrej Medic user avatar by
Andrej Medic
·
Jul. 22, 16 · Tutorial
Like (1)
Save
Tweet
Share
9.36K 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.

Popular on DZone

  • ChatGPT: The Unexpected API Test Automation Help
  • AWS Cloud Migration: Best Practices and Pitfalls to Avoid
  • How to Secure Your CI/CD Pipeline
  • Select ChatGPT From SQL? You Bet!

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: