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.LazyScopedRegistration
1.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>();
}
}