Simplify Configuration Management in .NET: Reading appsettings.json Without Dependency Injection

This guide demonstrates how to read the appsettings.json configuration file in a .NET application without using Dependency Injection. It involves four main steps:

Step 1: Add NuGet Packages

Make sure you have the necessary packages installed. You can add them via the NuGet Package Manager:

  • Microsoft.Extensions.Configuration

  • Microsoft.Extensions.Configuration.Json

Step 2: Create and Configure ConfigurationBuilder

First, you need to set up the ConfigurationBuilder to read the appsettings.json file.

using System;
using Microsoft.Extensions.Configuration;

// Initialize configuration
static IConfigurationRoot configuration;

var builder = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory) // Set the base path for the file
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); // Add the JSON file

configuration = builder.Build(); // Build the configuration

Step 3: Create a Method to Get Configuration Values

Create a method that takes a key as a parameter and returns the corresponding configuration value.

Step 4: Read and Display a Setting

Use the method created in the previous step to read a setting from the appsettings.json file and display it.

Full Code

Here's the complete code put together:

In this code:

  • Step 1 ensures you have the required packages.

  • Step 2 sets up the ConfigurationBuilder to read the appsettings.json file.

  • Step 3 provides a method to get configuration values by key.

  • Step 4 retrieves a specific setting and prints it to the console.

This approach allows you to read configuration settings from appsettings.json without using Dependency Injection, utilizing top-level statements to simplify your code.

Last updated