Small .NET Standard library to easy access to all environment variables you need.
Targets .NET 5, .NET Standard 2.1, .NET Core 3.1
Install with NuGet Package Manager Console
Install-Package EnvironmentVariables
Install with .NET CLI
dotnet add package EnvironmentVariables
Use public properties, not fields. Add Env
attribute with variable name to every property you want to get from environment.
using EnvironmentVariables;
public class EnvConfig
{
[Env("ASPNETCORE_ENVIRONMENT")]
public string AspNetCoreEnvironment { get; set; }
[Env("MY_ENV_INT")]
public int MyEnvInt { get; set; }
[Env("MY_ENV_BOOL")]
public bool MyEnvBool { get; set; }
[Env("MY_ENV_STRING_ARRAY")]
public string[] MyEnvStringArray { get; set; }
[Env("MY_ENV_INT_DICT")]
public Dictionary<int, string> MyEnvIntStrDictionary { get; set; }
}
Create new EnvironmentProvider
with class your crated earlier as a type parameter.
using EnvironmentVariables;
var provider = new EnvironmentProvider<EnvConfig>();
Access variables with Values
property
Console.WriteLine(provider.Values.AspNetCoreEnvironment);
//Development
Console.WriteLine(provider.Values.MyEnvInt);
//123
Console.WriteLine(provider.Values.MyEnvBool);
//True
You can easily add provider to your services
services.AddSingleton<EnvironmentProvider<EnvConfig>>();
or POCO class
services.AddSingleton<EnvConfig>(
_ => new EnvironmentProvider<EnvConfig>().Values
);
This library supports:
string
- all built-in value types (
bool
,int
,long
,float
,double
,decimal
, etc.) - collections (
IEnumerable
,Array
,List
, etc.) Dictionary
Enum
Nullable<>
You can check Tests
project to make sure that particular type is supported.
For collections in your environment variables use ,
or ;
as delimiter:
one,two,three
one;two;three
For dictionaries in your environment variables use =
or :
as delimiter between key and value:
firstkey=123;secondkey=321;thirdkey=0
1:true, 2:false, 3:true
Converter ignores spaces so feel free to use it anywhere you want.
You may specify the function that will be used to access variables values
var provider = new EnvironmentProvider<EnvConfig>() {
EnvProvider = name => ThisIsMyFunctionToAccessTheValues(name)
};
Use selflog for debugging
var provider = new EnvironmentProvider<EnvConfig>() {
SelfLog = log => Console.WriteLine(log)
};
Use Reload
to reload values from environment
provider.Reload();