How to inject configuration once in the Specflow?

Viewed 2373

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?

1 Answers

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);
}
Related