I'm using the .NET Core 1.1 in my API and am struggling with a problem:
- I need to have two levels of configurations:
appsettings.json
and environment variables. - I want to use the DI for my configurations via
IOptions
. - I need environment variables to override
appsettings.json
values.
So I do it like this so far:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Something here
services.Configure<ConnectionConfiguration>(options =>
Configuration.GetSection("ConnectionStrings").Bind(options));
// Something there
}
With my appsettings.json
composed like this
{
"ConnectionStrings": {
"ElasticSearchUrl": "http://localhost:4200",
"ElasticSearchIndexName": "myindex",
"PgSqlConnectionString": "blablabla"
}
}
I get all the configurations mapped to my class ConnectionConfiguration.cs
. But I cannot get the environment variables to be mapped as well. I tried the names like: ConnectionStrings:ElasticSearchUrl
, ElasticSearchUrl
, even tried specifying the prefix to .AddEnvironmentVariables("ConnectionStrings")
without any result.
How should I name the environment variables so it can be mapped with services.Configure<TConfiguration>()
?
System.Environment.GetEnvironmentVariables()
. – Biforate.GetSection
works, but the variables are so wrong ((( – Biforate.AddEnvironmentVariables(prefix:"you-prefix");
and read required env variable likeconfiguration["env-variable-name-without-prefix"]
But I did not get the correct value. What i'm doing wrong here? – Diphenylhydantoin