I want to use the IHostingEnvironment
and ConfigurationBuilder
in my functional test project, so that depending on the environment the functional tests run using a different set of configuration. I want to make use of the code below:
public IConfigurationRoot ConfigureConfiguration(IHostingEnvironment hostingEnvironment)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
.AddEnvironmentVariables();
return builder.Build();
}
I want to have an appSettings.json
and appSettings.Production.json
file to point my functional tests at production. Is this possible? How can it be achieved? I would need an instance of IHostingEnvironment
.
Using IConfiguration The IConfiguration is available in the dependency injection (DI) container, so you can directly access JSON properties by simply injecting IConfiguration in the constructor of a controller or class. It represents a set of key/value application configuration properties.
Supports Multiple Languages: You can use C#, F#, and Visual Basic programming languages to develop . NET Core applications. You can use your favorite IDE, including Visual Studio 2017/2019, Visual Studio Code, Sublime Text, Vim, etc.
You can use the ConfigurationBuilder
in a test project with a couple of steps. I don't think you will need the IHostingEnvironment
interface itself.
First, add two NuGet packages to your project which have the ConfigurationBuilder
extension methods:
"dependencies": {
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc1-final",
"Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final"
}
Second, put your desired environment variables into the test project's properties:
Then you can create your own builder in the test project:
private readonly IConfigurationRoot _configuration;
public BuildConfig()
{
var environmentName = Environment.GetEnvironmentVariable("Hosting:Environment");
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{environmentName}.json", true)
.AddEnvironmentVariables();
_configuration = config.Build();
}
If you want to use precisely the same settings file (not a copy), then you'll need to add in a path to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With