Utils.EnvironmentManager 4.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Utils.EnvironmentManager --version 4.0.1                
NuGet\Install-Package Utils.EnvironmentManager -Version 4.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Utils.EnvironmentManager" Version="4.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Utils.EnvironmentManager --version 4.0.1                
#r "nuget: Utils.EnvironmentManager, 4.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Utils.EnvironmentManager as a Cake Addin
#addin nuget:?package=Utils.EnvironmentManager&version=4.0.1

// Install Utils.EnvironmentManager as a Cake Tool
#tool nuget:?package=Utils.EnvironmentManager&version=4.0.1                

Project logo

Utils.EnvironmentManager

CodeFactor NuGet version License


Utils.EnvironmentManager is a C# library that provides robust management of environment variables with type conversion, logging, and mapping capabilities. It leverages AutoMapper to seamlessly convert environment variable values to strongly-typed objects, making it easier to handle configuration settings across various environments.

Note This documentation assumes a basic understanding of AutoMapper library. AutoMapper docs

Getting Started

EnvManager Class (Instance-Based)

The EnvManager class implements IEnvManager and provides a concrete implementation for managing environment variables.

Methods

public object Get(Type type, string variableName, bool raiseException = false);
public T Get<T>(string variableName, bool raiseException = false);

public object GetRequired(Type type, string variableName);
public T GetRequired<T>(string variableName);

Example: Basic Usage

using EnvironmentManager.Core;

public class Example
{
    public static void Main()
    {
        var envManager = new EnvManager();

        Environment.SetEnvironmentVariable("NUMBER", "131");
        int number = envManager.Get<int>("NUMBER");
        Console.WriteLine($"Number: {number}.");
    }
}
// The example displays the following output:
// Number: 131.

EnvManager Class (Static)

For convenience, Utils.EnvironmentManager provides a static EnvManager class that can be used without instantiating an object.

Methods

public static object Get(Type type, string variableName, bool raiseException = false);
public static T Get<T>(string variableName, bool raiseException = false);

public static object GetRequired(Type type, string variableName);
public static T GetRequired<T>(string variableName);

Example: Static Usage

using EnvironmentManager.Static;

public class Example
{
    public static void Main()
    {
        Environment.SetEnvironmentVariable("NUMBER", "131");
        int number = EnvManager.Get<int>("NUMBER");
        Console.WriteLine($"Number: {number}.");
    }
}
// The example displays the following output:
// Number: 131.

Enum Support

The library also supports retrieving environment variables that are associated with enum values using custom attributes.

Methods

public static dynamic Get(this Enum key, IEnvManager? envManager = null)
public static object Get(this Enum key, Type type, IEnvManager? envManager = null)
public static T Get<T>(this Enum key, IEnvManager? envManager = null)

public static dynamic GetRequired(this Enum key, IEnvManager? envManager = null)
public static object GetRequired(this Enum key, Type type, IEnvManager? envManager = null)
public static T GetRequired<T>(this Enum key, IEnvManager? envManager = null)

Example: Enum Support

using EnvironmentManager.Attributes;
using EnvironmentManager.Extensions;

public class Example
{
    public enum Env
    {
        [EnvironmentVariable(typeof(int), isRequired: true)]
        NUMBER
    }

    public static void Main()
    {
        Environment.SetEnvironmentVariable("NUMBER", "131");

        int number = Env.NUMBER.Get<int>();

        Console.WriteLine($"Number: {number}.");
    }
}
// The example displays the following output:
// Number: 131.

Custom Mapping Configuration

You can customize how environment variables are mapped to specific types using the EnvManagerMappingConfigurator.

Example: Custom Mapping Configuration

using EnvironmentManager.Configuration;

public class Example
{
    public static void Main()
    {
        Environment.SetEnvironmentVariable("INTEGER_ARRAY", "32, 6, 5, 23");

        var configuration = new EnvManagerMappingConfigurator()
            .CreateMapFor<int[]>(x => x.Split(',', StringSplitOptions.RemoveEmptyEntries)
                .Select(int.Parse)
                .ToArray<int>()
            )
            .Build();

        var envManager = new Core.EnvManager(configuration);

        Static.EnvManager.Initialize(envManager);
        // Static.EnvManager.Initialize(configuration);    // Or can pass configuration directly

        // Now you can retrieve environment variables with custom mapping
        int[] integerArrayViaStatic = Static.EnvManager.Get<int[]>("INTEGER_ARRAY");
        int[] integerArrayViaInstance = envManager.Get<int[]>("INTEGER_ARRAY");

        Console.WriteLine($"Integer array via static manager: {string.Join(", ", integerArrayViaStatic)}.");
        Console.WriteLine($"Integer array via instance manager: {string.Join(", ", integerArrayViaInstance)}.");
    }
}
// The example displays the following output:
// Integer array via static manager: 32, 6, 5, 23.
// Integer array via instance manager: 32, 6, 5, 23.

Logging

The library integrates with Microsoft.Extensions.Logging to provide logging for operations involving environment variables. You can supply your own ILogger<IEnvManager> instance when initializing EnvManager. If no logger is provided, a default instance of NullLogger<EnvManager> is used, which means no logging output will be produced.

Example: Logging

Note: In this example using Microsoft.Extensions.Logging.Console package.

using EnvironmentManager.Core;
using Microsoft.Extensions.Logging;

public class Example
{
    public static void Main()
    {
        Environment.SetEnvironmentVariable("ENVIRONMENT", "environment");

        var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
        var logger = loggerFactory.CreateLogger<IEnvManager>();

        var envManager = new EnvManager(logger: logger);

        string environment = envManager.Get<string>("INVALID_ENVIRONMENT");
        if (!string.IsNullOrEmpty(environment))
        {
            Console.WriteLine($"Environment: {environment}");
        }
    }
}
// The example displays the following output:
// warn: EnvironmentManager.Core.IEnvManager[0]
//       Environment variable 'INVALID_ENVIRONMENT' is null or empty. Trying return default value.

Example: Without logging If you wish to use the default logger (which won't produce any log output):

var manager = new EnvManager();

Logging Scenarios

Here are some situations where the EnvManager logs information:

  1. Warning: If an environment variable is null or empty and the raiseException parameter is set to false, a warning log will be generated.
  • Log Message: "Environment variable '{VariableName}' is null or empty. Trying return default value"
  1. Error: If there's a failed conversion of an environment variable and the raiseException parameter is set to false, an error log will be created.
  • Log Message: "Failed to convert environment variable '{VariableName}' to type '{Type}'. Trying return default value."

In both scenarios, the actual variable name and type (if applicable) will replace the placeholders {VariableName} and {Type}.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on Utils.EnvironmentManager:

Package Downloads
ConfiguredSqlConnection

The NuGet package is a collection of utilities for working with SQL Server database connections using environment settings and secure connection strings.

BNBParty.GraphQLClient

GraphQL Client for BNBParty .NET

EthSmartContractIO.SecretsProvider

A EthSmartContractIO module, that facilitates the secure creation of an Ethereum account and the extraction of secrets.

DownloaderV3.Source.CovalentDocument

The module for fetching, decoding, and saving blockchain event data using Covalent API in the DownloaderV3 system.

DownloaderV3.Source.CovalentLastBlock

The module for fetching the latest block data using Covalent API in the DownloaderV3 system.<

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
4.1.0 174 10/22/2024
4.0.1 612 8/27/2024
3.0.4 622 6/9/2024
3.0.3 86 6/9/2024
3.0.2 100 6/8/2024
3.0.1 96 6/6/2024
3.0.0 155 6/3/2024
2.0.1 3,892 8/7/2023
2.0.0 151 8/6/2023
1.1.0 2,538 6/15/2023
1.0.0 700 5/15/2023