DDank
DDank

Reputation: 191

Load .env variables in .NET6 program.cs

Instead of using appsettings.json, I have switched to .env for my secrets because it is easier to configure with docker.

How can I inject the .env file into the builder in my .NET6 application? My current implementation is screenshotted below. But it does not work.

enter image description here

Upvotes: 2

Views: 3279

Answers (2)

zion
zion

Reputation: 313

An external library or custom code is necessary for loading .env values. There is no built-in .NET feature to handle .env files.

Upvotes: 0

Hervé
Hervé

Reputation: 1018

I suggest you to prefix your .env variables to avoid conflits and loading unnecessary ones.

MY_PREFIX__MY_SECTION__MY_VARIABLE=foo
var config = builder.Configuration
     // only loads variables starting with your prefix
    .AddEnvironmentVariables(s => s.Prefix = "MY_PREFIX__")
    .Build();

Then, you need to define a DTO that represents your environement.

// needed in order to use ConfigurationKeyNameAttribute
using Microsoft.Extensions.Configuration;


public record MyEnv
{
    // don't specify neither your prefix nor the section here
    [ConfigurationKeyName("MY_VARIABLE")]
    public string MyVariable { get; init; }
}

and

var section = configuration.GetSection("MY_SECTION");

services.Configure<MyEnv>(section);

You can now use it in your services like so

public class MyService
{
     private readonly MyEnv _env;

     public MyService(IOptions<MyEnv> config)
     {
         _env = config.Value;
     }
}

Upvotes: 2

Related Questions