在 BeforeScenario 属性挂钩处将驱动程序添加到服务(SpecFlow.DependencyInjection 的 DI 容器)

Add driver to service (DI container by SpecFlow.DependencyInjection) at BeforeScenario attribute hooks

提问人:duy123a 提问时间:11/6/2023 最后编辑:Greg Burghardtduy123a 更新时间:11/15/2023 访问量:28

问:

我正在使用 SpecFlow.DependencyInjection

我在 ScenarioDependencies 属性中创建并添加了服务,如下所示

[ScenarioDependencies]
public static IServiceCollection CreateServices()
{
    var services = new ServiceCollection();

    // Add various stuffs here

    return services;
}

问题是方法(CreateServices)在BeforeScenario属性之前运行,我也在使用这个库:SpecFlow.Contrib.Variants允许我选择要使用的驱动程序。

通常在 BeforeScenario 钩子上,我编写的代码如下

[BeforeScenario]
public void BeforeScenario()
{
    _scenarioContext.TryGetValue("Browser", out var browser);

    switch (browser)
    {
        case "Chrome":
            _driver = SetupChromeDriver();
            break;
        case "Firefox":
            _driver = SetupFirefoxDriver();
            break;
        default:
            _driver = SetupChromeDriver();
            break;
    }
    _scenarioContext.ScenarioContainer.RegisterInstanceAs(_driver);
}

但是使用 Solidtoken/SpecFlow.DependencyInjection 使不再起作用,我无法在 CreateServices() 方法中将其注册到服务。_scenarioContext.ScenarioContainer.RegisterInstanceAs

如何将驱动程序重新绑定到 DI 容器?

我希望可以在构造函数中捕获它以供以后使用 喜欢

public void DoSomething(IWebDriver driver)
{
    _driver = driver
    // use driver do something else
}
C# selenium-webdriver 依赖注入 自动测试 specflow

评论

0赞 Greg Burghardt 11/15/2023
为什么还需要 ServicesCollection 对象?为什么现在像以前一样使用场景容器?方案容器是 DI 容器。
0赞 duy123a 11/16/2023
我知道这一点,但我的老板希望(强迫)我使用 Microsoft DI 而不是 Bodi(默认方案容器)。我是奴隶,不能争论,你知道的.~。
0赞 Greg Burghardt 11/16/2023
为什么不在 ScenarioDependencies 钩子中注册驱动程序?
0赞 Greg Burghardt 11/16/2023
更具体地说,为什么不在钩子内部注册 Web 驱动程序呢?IServicesCollection[ScenarioDependencies]

答: 暂无答案