Sunday, 19 August 2018

ConfigurationManager for .Net Core

.Net Core is changing a lot of the underlying technology for .Net developers migrating to this development environment. System.Configuration.ConfigurationManager class is gone and web.config and app.config files, which are XML-based are primrily replaced with .json files, at least in Asp.NET Core 2 for example. Let's look at how we can implement a class to let you at least be able to read AppSettings in your applicationSettings.json file which can be later refined. This implementation is my first version.

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System.IO;
using System.Linq;

namespace WebApplication1
{

    public static class ConfigurationManager
    {

        private static IConfiguration _configuration;

        private static string _basePath;

        private static string[] _configFileNames;

        public static void SetBasePath(IHostingEnvironment hostingEnvironment)
        {
            _basePath = hostingEnvironment.ContentRootPath;
            _configuration = null;

            //fix base path
            _configuration = GetConfigurationObject();
        }

        public static void SetApplicationConfigFiles(params string[] configFileNames)
        {
            _configFileNames = configFileNames;
        }

        public static IConfiguration AppSettings
        {
            get
            {
                if (_configuration != null)
                    return _configuration;

                _configuration = GetConfigurationObject();
                return _configuration;
            }
        }

        private static IConfiguration GetConfigurationObject()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(_basePath ?? Directory.GetCurrentDirectory());
            if (_configFileNames != null && _configFileNames.Any())
            {
                foreach (var configFile in _configFileNames)
                {
                    builder.AddJsonFile(configFile, true, true);
                }
            }
            else
                builder.AddJsonFile("appsettings.json", false, true);
            return builder.Build(); 
              
        }
    }
}

We can then easily get app settings from our config file:

  string endPointUri = ConfigurationManager.AppSettings["EmployeeWSEndpointUri"];

Sample appsettings.json file:
  {
  "Logging": {
    "IncludeScopes": false,
    "Debug": {
      "LogLevel": {
        "Default": "Warning"
      }
    },
    "Console": {
      "LogLevel": {
        "Default": "Warning"
      }
    }
  },
  "EmployeeWSEndpointUri": "https://someserver.somedomain.no/someproduct/somewcfservice.svc"

}

 
If you have nested config settings, you can refer to these using the syntax SomeAppSetting:SomeSubAppSetting, like "Logging:Debug:LogLevel:Default".
Share this article on LinkedIn.

No comments:

Post a Comment