I build and register configuration with my custom values:
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
container.RegisterInstanceAs<IConfiguration>(configuration);
this is done inside method with [BeforeScenario(Order = 1)]
annotation, I'd like to do it in method annotated by [BeforeTestRun]
tag, but this one needs to be static. This means that I can't inject BoDi
DI container into this method.
Thus how to load the configuration only once per test run and make it avaialble everywhere by DI container?
Registering the configuration once per scenario is how SpecFlow is meant to work so tests are thread safe and can be run in parallel. That being said, reading a config file should be pretty safe, even in a multi-threaded environment. You can initialize the config once using a static field, and then register the same instance before each scenario:
private static IConfiguration config;
[BeforeScenario]
public void CreateConfig()
{
if (config == null)
{
config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
}
container.RegisterInstanceAs<IConfiguration>(config);
}
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