Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow to bind a configuration class with the keys of the .env file #73

Closed
MrDave1999 opened this issue Apr 16, 2022 · 0 comments · Fixed by #92
Closed

Allow to bind a configuration class with the keys of the .env file #73

MrDave1999 opened this issue Apr 16, 2022 · 0 comments · Fixed by #92
Labels
feature New feature or request
Milestone

Comments

@MrDave1999
Copy link
Owner

MrDave1999 commented Apr 16, 2022

It would be nice if the keys could be accessed through a configuration class, for example:

class AppSettings
{
      public string ConnectionString { get; set; }
      public string JwtSecret { get; set; }
}

new EnvLoader().Load();
AppSettings settings = new EnvBinder.Bind<AppSettings>();
string key1 = settings.ConnectionString;
string key2 = settings.JwtSecret;

Bind is just a method of the EnvBinder class and would be responsible for binding the provider environment variables to the configuration class (in this case it would be AppSettings).

Of course, for the above code to work, the .env file should look like this:

ConnectionString=server=localhost; user=root; password=1234; port=3306
JwtSecret=1234tokenExample

In fact, there is no standard that tells us how to write the key names in an .env file, there is none. Normally a convention is followed:

# UpperCase + SnakeCase
KEY_NAME=VALUE

But it is not mandatory. Each project may name the keys in one way or another.

You may want to name your keys using this convention: KEY_NAME=VALUE (UpperCase + SnakeCase) and at the same time you want to name the properties in Pascal Case, therefore, you will have to associate an attribute (or decorator) to each property of the configuration class:

class AppSettings
{
      [EnvKey("CONNECTION_STRING")]
      public string ConnectionString { get; set; }

      [EnvKey("JWT_SECRET")]
      public string JwtSecret { get; set; }
}

It is necessary to embed the name of the real key to each property, since this way the EnvBinder.Bind method will be able to access the real key and set the value in the property.

The EnvKey attribute should only be used when the writing style of the keys of an .env file does not match that of the properties of a class (such as AppSettings).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
1 participant