I'm trying to run my Specflow tests in parallel. I've created an Assembly.cs file with
[assembly: Parallelizable(ParallelScope.Fixtures)]
[assembly: LevelOfParallelism(10)]
The code snippet below gives me the "An object has been resolved for this interface already" error when the tests are run in parallel, in the CreateTestData()
method, at the line with _container.RegisterInstanceAs(_driver, typeof(IWebDriver));
. If I run the tests sequentially, they pass.
public class BootstrapSelenium
{
private static IObjectContainer _container = new ObjectContainer();
private static IWebDriver? _driver;
public BootstrapSelenium(IObjectContainer container) => _container = container;
[BeforeTestRun]
public static void LoadDriver()
{
var appSettings = new AppSettings();
Configuration.Bind(appSettings);
_container.RegisterInstanceAs(appSettings, typeof(AppSettings));
}
[BeforeScenario]
public void CreateTestData()
{
_driver = CreateChromeDriver();
_container.RegisterInstanceAs(_driver, typeof(IWebDriver));
}
[AfterScenario]
public void Dispose()
{
_driver?.Close();
}
[AfterTestRun]
public static void CloseAll()
{
_driver?.Quit();
}
private IWebDriver CreateChromeDriver()
{
var options = new ChromeOptions();
options.AddArguments("--start-maximized");
options.AddArgument("no-sandbox");
options.AddArguments("--disable-gpu");
var driver = new ChromeDriver(options);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
return driver;
}
}
You can try to add [ThreadStatic]
to mark the _container and _driver fields. In this way, these fields will be unique for each thread. More details about ThreadStatic attribute can be found here.
[ThreadStatic]
private static IObjectContainer _container = new ObjectContainer();
[ThreadStatic]
private static IWebDriver? _driver;