8
votes

The Microsoft documentation states that

App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the Values collection in the local.settings.json file. In both environments, local and Azure, GetEnvironmentVariable("") retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains { "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }.

The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use GetEnvironmentVariable as shown here.

It is not stated why it is the recommended way.

  • Does it have performance advantages?
  • Is there is an instance where reading from AppSettings would result in an empty value?
  • Is it just for compatibility with different configuration formats (i.e., json, xml, etc)?

Or do I just accept this as a fact of life without knowing why?

2

2 Answers

6
votes

Does it have performance advantages?

I will say generally it does based on my test. GetEnvironmentVariable is a little faster than ConfigurationManager, on my pc(100k times) its average execution time is about 20μs shorter and on Azure(B1 app service plan, 10k times) is about 12μs shorter . It's a statistic conclusion as ConfigurationManager can be faster sometimes.

Is there is an instance where reading from AppSettings would result in an empty value?

If values to be read are set as expected, there may be only one scenario that we get null by using ConfigurationManager--In v2 function, where it's not useful any more.

Is it just for compatibility with different configuration formats (i.e., json, xml, etc)?

GetEnvironmentVariable has no such ability and there's no requirement for format compatibility. It's by design that Azure functions get configuration from local.settings.json in local development, when function host starts, app settings in Values are imported into environment variables of current process. So no format consideration.

To conclude, GetEnvironmentVariable is

  • concise--no need to import assembly of System.Configuration to use ConfigurationManager.
  • universal--for both v1 and v2, local and Azure environment.(Not include ConnectionStrings in local.settings.json).
  • faster--probably not so reliable, I use simple loops to repeat trigger with Stopwatch to measure(all logs disabled).

Of course we can still leverage ConfigurationManager in v1 functions and we have to use it if we want to get ConnectionStrings locally.

0
votes

One motivation I can think of is that setting environment variables ensures sensitive information is not hard-coded in the source code repo.