- CATALOG -
Alica's dev blog
Building and passing connection string from environment variables

Connecting your application to the database is one of those one-time tasks that you need to do at the beginning of a project.

Here I provide you with a solution on how to connect to the database while reading the configuration from environment variables.

Actually, there are more ways how to store the configuration. You can just copy and paste the connection string to the application - which is of course not recommended. Or you can read the values from a configuration file like appsettings.json.

But what if you want to be able to “inject” the values from outside? Here, it is practical to use environment variables. In Kubernetes, for example, you can define environment variables for a container that then passes them to the application running inside of it.

Solution

First, we need to read the values from environment variables:

var dbServer = System.Environment.GetEnvironmentVariable("DB_SERVER");
var dbUser = System.Environment.GetEnvironmentVariable("DB_USER");
var dbPassword = System.Environment.GetEnvironmentVariable("DB_PASSWORD");
var dbName = System.Environment.GetEnvironmentVariable("DB_NAME");
var dbPort = System.Environment.GetEnvironmentVariable("DB_PORT");

To create the connection string itself, you can use connection string builders. For example, SqlClient (SQL Server) has such builder, Npgsql (Postgres) also has one.

The second option is to use website like ConnectionStrings.com that provides standard connection strings many databases.

Let’s put it all into one method:

public static string ReadConnectionStringFromEnvironmentVariables()
{
    var dbServer = System.Environment.GetEnvironmentVariable("DB_SERVER");
    var dbUser = System.Environment.GetEnvironmentVariable("DB_USER");
    var dbPassword = System.Environment.GetEnvironmentVariable("DB_PASSWORD");
    var dbName = System.Environment.GetEnvironmentVariable("DB_NAME");
    var dbPort = System.Environment.GetEnvironmentVariable("DB_PORT");

    // this is an example with connection string for Postgres
    return $"Server={dbServer};Database={dbName};Port={dbPort};User ID={dbUser};Password={dbPassword}";
}

Now we can use this connection string wherever we need. If we are using EF core, we call ReadConnectionStringFromEnvironmentVariables in ConfigureServices method in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddDbContext<ApiContext>(options =>
    {
        // something like 
        options.UseSqlServer(ReadConnectionStringFromEnvironmentVariables());

        // or
        options.UseNpgsql(ReadConnectionStringFromEnvironmentVariables());

        // or else...
    });

    ...
}

Last modified on 2021-10-01