Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject configuration once in the Specflow?

Tags:

c#

specflow

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?

like image 204
Yoda Avatar asked Oct 16 '25 18:10

Yoda


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);
}
like image 164
Greg Burghardt Avatar answered Oct 18 '25 08:10

Greg Burghardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!