Reputation: 1279
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.
Or do I just accept this as a fact of life without knowing why?
Upvotes: 13
Views: 5060
Reputation: 17800
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
System.Configuration
to use ConfigurationManager
.ConnectionStrings
in local.settings.json).Of course we can still leverage ConfigurationManager
in v1 functions and we have to use it if we want to get ConnectionStrings
locally.
Upvotes: 8
Reputation: 5870
One motivation I can think of is that setting environment variables ensures sensitive information is not hard-coded in the source code repo.
Upvotes: 0