Skip to content

A .NET library to load environment variables into a .NET object

License

Notifications You must be signed in to change notification settings

RichardD012/EnvMapper

Repository files navigation

EnvMapper

EnvMapper Build EnvMapper Tests License: MIT NuGet version

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.

Installation

Available on NuGet

Visual Studio:

PM> Install-Package EnvMapper

.NET CLI:

dotnet add package EnvMapper

Usage

Load env file

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.

Example

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.

About

A .NET library to load environment variables into a .NET object

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages