Configuration Model in c#

Configuration Model in c# , ANGULAR WITH CORE .NET AND MVC RAZOR ENGINE

 Configuration Model

Configuration data should live outside the application. If you feel the urge to
hardcode something, stop and think about the impact it may have on the scalability of
the application in the future. When we separate the configuration from the application, it
allows us to deploy the same code to do different things in different environments 

There is a saying "Don’t code hard, hardcode instead.”

As .NET developers, we should be familiar with the good old app.config and web.
config files, which offer a mechanism for a specific configuration for each application.
ASP.NET Core is no different, but with a much better mechanism for storing and
providing configuration data. In fact, the new configuration model in ASP.NET Core is
much more simplified, flexible, and extendable. Compared to its predecessors, it sets the
bar quite high. In laymen’s terms, it is just awesome.

I have been worked with ASP.NET for 3 years so still, I remember all these config files :😊

ASP.Net core provided configuration API for working with configuration with web apps based on name/value or key/value pair we will focus on understanding the basic concept of configuration in ASP.NET Core and how to leverage the provided API to read environment-specific configuration data from multiple sources into strongly typed objects.

Custom Configuration

Let's take an example to understand custom configuration, Consider below piece of code to understand the custom configuration

Add new JSON file in your root folder of the application and add below piece of the JSON structure
I have added customConfiguration.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Name": " Core Micro Services",
  "URL": "https://angularvscoredotnet.blogspot.com/",
  "Date": "13th August 2020"
   
}

and use the below piece of code to read this configuration file

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
namespace My_First_API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).

AddJsonFile("customConfiguration.json");

            var customconfig = configurationBuilder.Build();
            foreach (var item in customconfig.AsEnumerable())
            {
                Console.WriteLine($"{item.Key} -> {item.Value} ");
            }
            CreateHostBuilder(args).Build().Run();                     
            Console.ReadLine();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}


Configuration Providers

A configuration can be loaded from many different sources containing many different

formats. Configuration providers are responsible for passing the configuration in a specific format from a pre-defined source to the configuration model of ASP.NET Core. ASP.NET Core ships with default configuration providers out of the box, allowing a configuration to be loaded from files (JSON, XML, and INI formats), command-line arguments, environmental variables, in-memory .NET objects, encrypted user secret stores, the Azure Key Vault, and custom providers that we can create. Consider below piece of code

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
namespace My_First_API
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("customConfiguration.json")
                .AddXmlFile("customConfiguration.xml")
                .AddIniFile("customConfiguration.ini")
                .AddCommandLine(args) // this line will add command line arguement
                .AddEnvironmentVariables() // This line will add all the environment variables
                .AddInMemoryCollection()
                .AddUserSecrets("customConfigurationSecrets");
            var customconfig = configurationBuilder.Build();
            foreach (var item in customconfig.AsEnumerable())
            {
                Console.WriteLine($"{item.Key} -> {item.Value} ");
            }
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

Working with Changes

ASP.NET Core, it is important to understand that configuration data may change during runtime and we need our application to react to changes accordingly.

var configurationBuilder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile( x=> { x.Path = "customConfiguration.json"; x.ReloadOnChange = true; // this will reload change if any changes introduced at runtime } )


Conclusion

We have come to the end of yet another chapter where we learned exciting new things
about ASP.NET Core. In this chapter, we explored the basics of how the configuration
model works and how we can quickly load configuration data in any supported format
from multiple different sources.
We covered the eight built-in configuration providers that ship with ASP.NET Core
and learned how they could be used in conjunction with each other to override specific
values. In this chapter, we also learned how to build a custom configuration provider that
loads the settings used in legacy systems straight into the configuration model

Comments

Popular posts from this blog

How to disable table row in Angular

How to create XML file dynamically in c#.net?

How to get Array value in Angular ?