简体   繁体   English

SpecFlow:我可以动态地从 Specflow 的依赖注入中解析对象吗?

[英]SpecFlow: Can I resolve objects from Specflow's dependency-injection dynamically?

The typical way in SpecFlow to resolve dependencies is via constructor injection: SpecFlow 中解决依赖关系的典型方法是通过构造函数注入:

    public class DependentClass
    {
        private readonly DependencyClass dependency;

        public DependentClass(
            DependencyClass dependency)
        {
            this.dependency = dependency;
        }
    }

When the DependentClass is required, the DependencyClass is automatically created (assuming it can be resolved, etc etc).当需要 DependentClass 时,会自动创建 DependencyClass(假设它可以被解析,等等)。

What I'd like to do in some cases is to resolve an instance of a dynamically-determined class, eg:在某些情况下,我想做的是解析动态确定类的实例,例如:

        public DependentClass(
            TestThreadContext testThreadContext)
        {
            this.testThreadContext = testThreadContext;
        }

        public void ActOnDependency(Type dependencyType)
        {
            var dependency = this.testThreadContext.TestThreadContainer.Resolve(dependencyType);
            // ...and then call instance methods on the dependency
        }

However, when I do it like this, the IObjectContainer returned by this.testThreadContext.TestThreadContainer isn't the same one that is being used by the current test execution.但是,当我这样做时, this.testThreadContext.TestThreadContainer返回的IObjectContainer与当前测试执行使用的不同。

Is there any way to access the same IObjectContainer that SpecFlow is already using to resolve constructor dependencies, or any other way to resolve instances from that container?是否有任何方法可以访问 SpecFlow 已经用来解析构造函数依赖项的同一个IObjectContainer ,或者有任何其他方法可以从该容器中解析实例?

Instead of TestThreadContext , inject ScenarioContext .而不是TestThreadContext ,注入ScenarioContext This is the container used to resolve scenario-specific dependencies injected via constructor.这是用于解析通过构造函数注入的特定于场景的依赖项的容器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM