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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Building a Microservices API Gateway With YARP in ASP.NET Core Web API
  • Working With dotConnect for Oracle in ASP.NET Core
  • Alexa Skill With .NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way

Trending

  • A Modern Stack for Building Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • MCP Servers: The Technical Debt That Is Coming
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  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.0K 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
  • Alexa Skill With .NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!