ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Configuration Overview
    Advanced ProgrammingTopic 23 of 55

    Configuration Overview

    7 minread
    1,107words
    Intermediatelevel

    Configuration Overview in C#

    Configuration is a fundamental aspect of software development, especially for enterprise applications. In C#, configuration management involves specifying how the application should behave under different environments, such as development, testing, or production. This configuration typically includes settings like connection strings, file paths, logging options, application behavior, and other environment-specific values. The goal is to externalize these settings from the application's code so that they can be easily modified without changing the codebase.

    In .NET applications, configuration data is often stored in configuration files, such as XML-based files (app.config or web.config) or more modern approaches like JSON-based files (appsettings.json).


    1. Types of Configuration Files in C#

    A. App.config / Web.config

    In older versions of .NET (e.g., .NET Framework), XML-based configuration files like app.config and web.config were commonly used. These files store various configuration settings, including application-specific settings, security, database connections, and more.

    • app.config: Used in desktop applications (WinForms, WPF, Console apps).
    • web.config: Used in web applications (ASP.NET WebForms, MVC).
    Example of app.config (XML format):
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <appSettings>
        <add key="AppTitle" value="My Application" />
        <add key="MaxUsers" value="100" />
      </appSettings>
    
      <connectionStrings>
        <add name="DatabaseConnection" connectionString="Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;" providerName="System.Data.SqlClient" />
      </connectionStrings>
    
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
      </system.web>
    </configuration>
    
    • appSettings section: Holds simple key-value pairs that can be used throughout the application.
    • connectionStrings section: Stores database connection strings.
    • system.web section: Contains configuration settings specific to web applications, like compilation and authentication settings.

    These settings can be read at runtime using ConfigurationManager class in C#.

    using System.Configuration;
    
    string appTitle = ConfigurationManager.AppSettings["AppTitle"];
    string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
    

    B. appsettings.json

    With the introduction of .NET Core and .NET 5+, the configuration system has evolved. One of the major changes was the adoption of JSON as the default configuration file format, particularly for ASP.NET Core applications. The appsettings.json file is now commonly used to store application settings.

    Example of appsettings.json:
    {
      "AppSettings": {
        "AppTitle": "My Application",
        "MaxUsers": 100
      },
      "ConnectionStrings": {
        "DatabaseConnection": "Server=myServer;Database=myDB;User Id=myUser;Password=myPassword;"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      }
    }
    

    How to Access Configuration in .NET Core:

    In .NET Core (or .NET 5+), the appsettings.json file is accessed via IConfiguration interface.

    using Microsoft.Extensions.Configuration;
    
    public class MyService
    {
        private readonly IConfiguration _configuration;
    
        public MyService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void PrintAppTitle()
        {
            string appTitle = _configuration["AppSettings:AppTitle"];
            Console.WriteLine(appTitle);
        }
    }
    

    This system allows for easier binding of configuration data to objects, improved dependency injection, and greater flexibility in how configuration is structured and accessed.


    2. Key Configuration Concepts

    A. Configuration Hierarchy

    In modern .NET applications, configuration files can be nested and follow a hierarchical structure. This allows for more granular control over different sections of the application.

    For example, in appsettings.json, you can have nested sections, like:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=myDB;"
      },
      "AppSettings": {
        "Title": "My App"
      }
    }
    

    Accessing nested values would look like this:

    string logLevel = _configuration["Logging:LogLevel:Default"];
    

    B. Configuration Sources and Providers

    .NET supports multiple configuration providers, which allow different sources of configuration data, such as:

    • JSON files (appsettings.json, appsettings.{Environment}.json).
    • Environment variables.
    • Command-line arguments.
    • In-memory collections.
    • Custom configuration sources.

    For example, a common pattern in ASP.NET Core is to load configurations from multiple sources, with the last loaded source taking precedence.

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((context, config) =>
            {
                var environment = context.HostingEnvironment.EnvironmentName;
                config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{environment}.json", optional: true)
                      .AddEnvironmentVariables();
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
    

    C. Environment-Specific Configuration

    In .NET, you can have environment-specific configurations for different environments like Development, Staging, and Production. This is especially useful in cloud-based applications and when managing different configurations for different deployment environments.

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

    .NET automatically selects the appropriate configuration file based on the environment.

    For example:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=localhost;Database=devDB;"
      }
    }
    

    And for production:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=prodServer;Database=prodDB;"
      }
    }
    

    You can set the environment using the ASPNETCORE_ENVIRONMENT environment variable:

    set ASPNETCORE_ENVIRONMENT=Production
    

    D. Configuration Reloading

    In ASP.NET Core, configuration files such as appsettings.json can be reloaded automatically if they are changed. This is achieved through the reloadOnChange flag when adding configuration sources.

    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
    

    3. Accessing Configuration in C#

    In both .NET Framework and .NET Core, configuration can be accessed through different mechanisms.

    A. Accessing Configuration in .NET Framework

    In .NET Framework, configuration is typically accessed using ConfigurationManager class, which reads data from the app.config or web.config file.

    using System.Configuration;
    
    string appTitle = ConfigurationManager.AppSettings["AppTitle"];
    string connectionString = ConfigurationManager.ConnectionStrings["DatabaseConnection"].ConnectionString;
    

    B. Accessing Configuration in .NET Core

    In .NET Core, configuration is accessed using IConfiguration, which is part of the dependency injection system. You can inject IConfiguration into your classes to access configuration values.

    public class MyService
    {
        private readonly IConfiguration _configuration;
    
        public MyService(IConfiguration configuration)
        {
            _configuration = configuration;
        }
    
        public void PrintAppTitle()
        {
            string appTitle = _configuration["AppSettings:AppTitle"];
            Console.WriteLine(appTitle);
        }
    }
    

    4. Common Configuration Sections

    Here are a few common sections you might find in configuration files:

    A. Connection Strings

    Connection strings for databases, message brokers, and other services are often stored in the connectionStrings section.

    Example (in app.config or appsettings.json):

    <connectionStrings>
        <add name="MyDb" connectionString="Server=localhost;Database=MyDb;Integrated Security=True;" />
    </connectionStrings>
    

    Or in appsettings.json:

    {
      "ConnectionStrings": {
        "MyDb": "Server=localhost;Database=MyDb;Integrated Security=True;"
      }
    }
    

    B. Logging Configuration

    You can configure logging options in configuration files, such as the log level or the log file path.

    Example (in appsettings.json):

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning"
        }
      }
    }
    

    5. Summary

    • Configuration in C# is a way of managing application settings externally, allowing for easier maintenance and flexibility.
    • Configuration files include app.config, web.config, and appsettings.json (for .NET Core).
    • Environment-specific configurations allow different settings for different deployment environments (Development, Production, etc.).
    • .NET offers a flexible configuration system where settings can be loaded from various sources
    Previous topic 22
    Shared Assembly Deployment
    Next topic 24
    Configuration Files

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,107
      Code examples0
      DifficultyIntermediate