In this article, we will learn how to read database connection strings from different configuration sources in .NET applications.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

Loading a Configuration File

In .NET applications, we usually store connection strings and configuration in the appsettings.json file at the root of our project. For console applications, we will have to manually add them to our project. Also, we will have to make sure that the file gets copied to the output folder when building the application.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

Once the configuration file is added to the project output, we can build a Configuration object including our appsettings.json file as its configuration source. For that, we can use an instance of the ConfigurationBuilder class.

To add our appsettings.json file as a configuration provider using the JsonConfigurationProvider, let’s call the AddJsonFile() extension method on our configuration builder:

var builder = new ConfigurationBuilder();

builder.AddJsonFile("appsettings.json");
var configuration = builder.Build();

After that, calling the Build() method on the ConfigurationBuilder instance returns a Configuration object that we can use to read configuration values from the source.

How to Read Connection Strings From the ConnectionStrings Section

Once we have the configuration object, let’s use it to read values from the configured sources. For database connection strings, the standard way to store them in the JSON settings file is under the ConnectionStrings section:

{
  "ConnectionStrings": {
    "ProductsDb": "Server=myServer;Database=products;Trusted_Connection=True;",
    "UsersDb": "Server=myServer;Database=users;Trusted_Connection=True;"
  }
}

Then, let’s use the GetConnectionString() method of the Configuration object to read our connection string from the settings file:

IConfiguration configuration = builder.Build();
var connString = configuration.GetConnectionString("ProductsDb");

How to Read Connection Strings From a Custom Configuration Section

We can always decide to go for a different structure when arranging our configuration. In those cases our connection strings may be located under different sections of the settings file:

"Modules": {
  "Products": {
    "ConnectionStrings": {
      "Database": "Server=myServer;Database=products;Trusted_Connection=True;"
    }
  },
  "Users": {
    "ConnectionStrings": {
      "Database": "Server=myServer;Database=users;Trusted_Connection=True;"
    }
  }
}

Let’s use GetSection() and GetConnectionStrings() methods of the configuration object to access the connection strings in this new location:

var prodDb = configuration.GetSection("Modules:Products").GetConnectionString("Database");
var userDb = configuration.GetSection("Modules:Users").GetConnectionString("Database");

In a case where we do not want to use a ConnectionString property, we can arrange our configuration a bit differently:

{
  "Modules": {
    "Users": {
      "Database": "Server=myServer;Database=users;Trusted_Connection=True;"
    }
  }
}

Then, let’s use the square bracket notation on the configuration object to access our connection string directly:

var configuration = builder.Build();

var prodDb = configuration["Modules:Users:Database"];

Alternatively, let’s call the GetValue() extension method:

var prodDb = configuration.GetValue<string>("Modules:Users:Database");

Note that we need to have the Microsoft.Extensions.Configuration.Binder package installed in our project to use the GetValue() method.

How to Read Connection Strings From Environment Variables

Another common configuration source is the system’s environment variables. If we install the Microsoft.Extensions.Configuration.EnvironmentVariables package let’s use the AddEnvironmentVariables() extension method of the ConfigurationBuilder object to use environment variables as our configuration source:

var builder = new ConfigurationBuilder();

builder.AddEnvironmentVariables();
var configuration = builder.Build();

When setting up configuration using environment variables, we can still have nested sections using the double underscore __ as a section separator. Let’s define an environment variable for our connection string using the windows command line:

set ConnectionStrings__ProductsDb="Server=myServer;Database=products;Trusted_Connection=True;"

Then, let’s use the GetConnectionString() method or any of the other methods we have seen before to read the connection string:

var connString = configuration.GetConnectionString("ProductsDb");

How to Get Connection String in an ASP.NET Core Application

In an ASP.NET Core application, the WebApplicatioinBuilder takes care of setting up all the common configuration sources for us. Moreover, a configuration object will be added to the application’s service provider. Thanks to this, we will be able to inject our configuration into any of our application classes through the IConfiguration interface:

[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IConfiguration _configuration;

    public ProductsController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpGet]
    public IActionResult GetConnectionString()
    {
        var connString = _configuration.GetConnectionString("ProductsDb");

        // TODO: Use the connection string to access data.

        return Ok();
    }
}

In this controller, we inject an instance of the IConfiguration class into the controller constructor. Later, we use it to read a connection string using the GetConnectionString() method.

Conclusion

In this article, we have learned how to read configuration strings from an application settings JSON file. Also, we have learned how to read connection strings from environment variables through the .NET Core Configuration object.

Finally, we have learned how we can read connection strings in ASP.NET Core applications by injecting a configuration object in a controller class.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!