EnvVarInject

Build time environment variable injection for .net

  • C#
  • Fody
  • Nuget
  • Nunit

The Challenge

There are many cases when projects need some secret configuration and it's important that this configuration is not hardcoded in the source, there are existing solutions for this problem but none are easily implementable in a .Net portable class library. Portable class libraries target multiple platforms so do not have a uniform way of accessing configuration files on disk or environment variables at runtime. It can also be helpful to have access to information generated at build time from within your application, information such as build number, build configuration and last commit hash.

The Solution

Rather than loading configuration at runtime it would be easier if the variables where prepopulated with the important configuration information at build time, builds can be executed for various build configurations and deployment targets with different environment variable values. Using attributes the variables can be annotated with the name of the environment variable they will be replaced with.

Fody is a tool for manipulating and generating assemblies' IL, it allows extensibility in the form of weavers. Using a combination of Fody and a custom attribute any instance, static and readonly fields' values can be replaced in the IL with the value found in the specified environment variable.

By packaging and publishing the weaver to nuget it can be easily installed into any supported .Net project type, injecting the required build tasks and the custom attribute.