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

The typical way in SpecFlow to resolve dependencies is via constructor injection:

    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).

What I'd like to do in some cases is to resolve an instance of a dynamically-determined class, e.g:

        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.

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?



Solution 1:[1]

Instead of TestThreadContext, inject ScenarioContext. This is the container used to resolve scenario-specific dependencies injected via constructor.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Overlord Zurg