A .NET library to map environment variables to a C# object. This is useful when deploying to containerized environments where environment variables may be injected before starting up.
Available on NuGet
Visual Studio:
PM> Install-Package EnvMapper
.NET CLI:
dotnet add package EnvMapper
MapConfiguration()
will automatically search for environment variables and map them to a class decorated with System.Runtime.Serialization.DataMember
attributes. This supports overriding using the Name
and IsRequired
properties of the DataMemberAttribute
.
var config = EnvMapper.Env.MapConfiguration<TType>();
If properties that are marked as required are not found or are of the wrong type (ie a string
instead of an int
), a EnvMapperException
will be thrown, which contains a list of error properties.
Given the following example class:
[DataContract]
public class TestConfiguration
{
[DataMember(Name="Foo", IsRequired = true)]
public string? Foo { get; set; }
[DataMember]
public string? Bar { get; set; }
[DataMember(Name="Override")]
public string? OtherField { get; set; }
}
The following can be used to access the variables that are present as environment variables:
var config = EnvMapper.Env.MapConfiguration<TestConfiguration>();
Console.WriteLine($"Foo={config.Foo}");//This must be present
Console.WriteLine($"Bar={config.Bar}");//This may be present
Console.WriteLine($"Otherfield={config.OtherField}");//This may be present
Note: in the above example the variables that will be checked are Foo
, Bar
, and Override
. If there is an environment variable OtherField
, the reader will not check that as the DataMember signified on the variable should be Override
.