1

I'm trying to setup my Specflow (V. 3.0.155 beta) tests in a .Net Core 2.1 Web API and I'm following a structure I've used in some previous .Net Framework Web API projects I've worked on to do so.

But I'm running into trouble when I try to resolve my dependencies, it seems as though I'm moving out of scope so when I try to resolve something, i.e. my test data context, I get the following error from SpecFlow:

Message: SimpleInjector.ActivationException : The registered delegate for type ProjectNexusContext threw an exception. The ProjectNexusContext is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope. ----> SimpleInjector.ActivationException : The ProjectNexusContext is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.

Stack trace:

Result StackTrace: at SimpleInjector.InstanceProducer.GetInstance()
at SimpleInjector.Container.GetInstanceTService at ProjectNexus.ApplicationContext.ResolveT in C:\Users\dawes\source\repos\ProjectNexus\ProjectNexus\ApplicationContext.cs:line 18 at ProjectNexus.Engine.Specs.LifecycleTestHooks.AfterStep() in C:\Users\dawes\source\repos\ProjectNexus\ProjectNexus.Engine.Specs\LifecycleTestHooks.cs:line 37 at TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration) in D:\a\1\s\TechTalk.SpecFlow\Bindings\BindingInvoker.cs:line 73 at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.InvokeHook(IBindingInvoker invoker, IHookBinding hookBinding, HookType hookType) in D:\a\1\s\TechTalk.SpecFlow\Infrastructure\TestExecutionEngine.cs:line 246 at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.FireEvents(HookType hookType) in D:\a\1\s\TechTalk.SpecFlow\Infrastructure\TestExecutionEngine.cs:line 232 at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance) in D:\a\1\s\TechTalk.SpecFlow\Infrastructure\TestExecutionEngine.cs:line 367 at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.Step(StepDefinitionKeyword stepDefinitionKeyword, String keyword, String text, String multilineTextArg, Table tableArg) in D:\a\1\s\TechTalk.SpecFlow\Infrastructure\TestExecutionEngine.cs:line 475 at TechTalk.SpecFlow.TestRunner.Given(String text, String multilineTextArg, Table tableArg, String keyword) in D:\a\1\s\TechTalk.SpecFlow\TestRunner.cs:line 75 at ProjectNexus.Engine.Specs.Tests.Client.Authentication.LogInFeature.FeatureBackground() in C:\Users\dawes\source\repos\ProjectNexus\ProjectNexus.Engine.Specs\Tests\Client\Authentication\Log In.feature:line 7 at ProjectNexus.Engine.Specs.Tests.Client.Authentication.LogInFeature.LogInWithAValidUsernameAndPassword() in C:\Users\dawes\source\repos\ProjectNexus\ProjectNexus.Engine.Specs\Tests\Client\Authentication\Log In.feature:line 6 --ActivationException at SimpleInjector.Scope.GetScopelessInstance[TImplementation](ScopedRegistration1 registration) at SimpleInjector.Advanced.Internal.LazyScopedRegistration1.GetInstance(Scope scope) at lambda_method(Closure ) at SimpleInjector.InstanceProducer.GetInstance() Result Message: SimpleInjector.ActivationException : The registered delegate for type ProjectNexusContext threw an exception. The ProjectNexusContext is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope. ----> SimpleInjector.ActivationException : The ProjectNexusContext is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope. Result StandardOutput: Given The following users are stored in the database --- table step argument --- | Forneame | Surname | Username | | John | Smith | js001 | -> error: The registered delegate for type ProjectNexusContext threw an exception. The ProjectNexusContext is registered as 'Async Scoped' lifestyle, but the instance is requested outside the context of an active (Async Scoped) scope.

I'm using Simple Injector 4.4.2 and in my test project and I setup my container and register my instances in a static class method which is called in the BeforeTestRun SpecFlow life cycle hook.

Then in my BeforeScenario hook I'm beginning a new AsyncScopedLifestyle scope on said container which is to be used throughout for the given scenario. Next, In my AfterScenario hook I then dispose of this lifestyle. I've looked at the SimpleInjector documentation regarding this lifestyle and am aware that this exception is thrown when outside the context of an active scope but I cannot see why I'm outside the active context!

Upon inspecting the Scope in the BeforeStep hook, I can see that, although not disposed, the CurrentScope property in the ScopeManager is null so I'm clearly out of an active scope context.

This has never been an issue before and the code is exactly the same as in the aforementioned previous projects that go about using SimpleInjector in their test projects in exactly the same way. I even stepped through them and checked the scope in the BeforeStep hook and the CurrentScope in the ScopeManager was the scope so they're obviously not out of scope at that point.

I was hoping someone might see something I'm missing or have some suggestions as to how to go about resolving this.

I've included the code for my SpecFlow hooks and IoC Setup below:

SpecFlow hooks:

[Binding]
public class LifecycleTestHooks
{

[BeforeTestRun]
public static void BeforeTestRun()
{
    TestIocConfiguration.Configure();
}

[BeforeScenario]
public void BeforeScenario()
{
    TestIocConfiguration.StartExecutionScope();
}

[BeforeStep]
public void BeforeStep()
{
    var projectDbContext = ApplicationContext.Resolve<ProjectNexusContext>();
    projectDbContext.Database.BeginTransaction();
}

[AfterStep]
public void AfterStep()
{
    var projectDbContext = ApplicationContext.Resolve<ProjectNexusContext>();
    if (projectDbContext.Database.CurrentTransaction != null)
    {
        try
        {
            projectDbContext.Database.CommitTransaction();
        }
        catch (Exception)
        {
            projectDbContext.Database.RollbackTransaction();
            throw;
        }
    }
    TestIocConfiguration.CheckExecutionScope();
}

[AfterScenario]
public void AfterScenario()
{
    TestIocConfiguration.EndExecutionScope();
}
}

IoC Setup

 public class TestIocConfiguration
    {
        static Container container;

        public static void Configure()
        {
            container = ApplicationContext.Container;
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            EngineInitialisation.Initialise();

            container.Options.AllowOverridingRegistrations = true;

            RegisterTestDatabaseContext();
            RegisterTestApplicationConfiguration();
            RegisterTestLdapConnectionService();
            RegisterTestContext();
        }

        private static void RegisterTestDatabaseContext()
        {
            var testContext =
                new ProjectNexusContext(new TestContextHelper().GetDbContextOptionsBuilder());
            testContext.Database.OpenConnection();
            testContext.Database.EnsureCreated();
            container.Register<ProjectNexusContext>(() => testContext, Lifestyle.Scoped);
        }

        private static void RegisterTestLdapConnectionService()
        {
            container.Register<ILdapConnectionService, TestLdapConnectionService>(Lifestyle.Scoped);
        }

        private static void RegisterTestApplicationConfiguration()
        {
            var appConfig = new ApplicationConfiguration
            {
                LdapHost = "",
                LdapPort = 0,
                ApplicationSecret = "TestSecret",
                TokenExpirationDays = 1
            };
            container.Register<ApplicationConfiguration>(() => appConfig, Lifestyle.Scoped);
        }

        private static void RegisterTestContext()
        {
            container.Register<TestContext>(Lifestyle.Singleton);
        }

        public static Scope StartExecutionScope()
        {
            return AsyncScopedLifestyle.BeginScope(container);
        }

        public static void EndExecutionScope()
        {
            Lifestyle.Scoped.GetCurrentScope(container)?.Dispose();
        }
    }

Application Context

public class ApplicationContext
{
    public static readonly Container Container;
    public static readonly Mapper Mapper;

    static ApplicationContext()
    {
        Container = new Container();
    }

    public static T Resolve<T>() where T : class
    {
        return Container.GetInstance<T>();
    }

    public static Cast Resolve<T, Cast>()
        where Cast : T
        where T : class
    {
        return (Cast)Container.GetInstance<T>();
    }
}
4
  • Please post the full stack trace of the exception (and all its inner exceptions)
    – Steven
    Dec 20, 2018 at 18:36
  • @Steven I've amended the question to include the requested details.
    – Adam
    Dec 20, 2018 at 19:51
  • Is there any complete demo to reproduce your issue?
    – Edward
    Dec 21, 2018 at 5:24
  • @TaoZhou due to the nature of this project, I'm unable to provide the exact code I'm using. However, I've created a separate test project you can run which recreates the issue and demonstrates exactly how I'm doing things and the issues I'm having. Here is a link to said project
    – Adam
    Dec 22, 2018 at 2:42

1 Answer 1

1

Before each spec you will need to create a new Container to be used as I don't think re-using will do what your expecting with the current set up.

You can add a method called SetContainer in your ApplicationContext like so:

public static void SetContainer(Container container)
{
    Container = container;
}

And then in your BeforeScenario hook you can run your IoC configuration, but new up a container and use your SetContainer method

UPDATE: It seems with Specflow 3-beta, the active scope gets disposed as soon as it leaves the test hook method (e.g. BeforeScenario)

For now you can register your instances with a singleton lifestyle, and use a new container for each test (like you can do with the suggestion I made above).

I tried identical code in Specflow 2.3.2 and it works fine, but breaks in Specflow 3-beta.

1
  • This answer makes me horny :)
    – ViqMontana
    Jan 8, 2019 at 20:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.