Fix #2600 by preserving ExecutionContext and reuse it for subsequent binding method invocations #2658
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR fixes #2600 by saving and reusing the ExecutionContext for the subsequent binding method invocations. ExecutionContext is pretty complex and hard to understand and also the behavior of
AsyncLocal<T>
is not straightforward to understand.The bottom line is:
AsyncLocal<T>
now works as in SpecFlow v3 (and is it supposed to): you can change the value in ctor and sync step definitions, but the changes in async step definitions are discarded (this is how ExecutionContext works).If you want to use
AsyncLocal<T>
and be able to change it in sync/async step definitions, you should useAsyncLocal<StrongBox<T>>
and initialize it in ctor, like:A bit more tech detail (also included in
BindingDelegateInvoker
as comment):To be able to simulate the behavior of sequential async or sync steps in a test, we need to ensure that the next step continues with the ExecutionContext that the previous step finished with.
Without preserving the ExecutionContext this would not happen because the async methods all the way up to the generated test method (for example this method) are discarding the ExecutionContext changes at the end, so the next step would start with an "empty" ExecutionContext again.
It is important that no methods from here (until the user's binding method) is marked with 'async' otherwise that would again discard the ExecutionContext.
The ExecutionContext only flows down, so async binding methods cannot directly change it, but even if all binding method is async the constructor of the binding classes are run in sync, so they should be able to change the ExecutionContext. (The binding classes are created as part of the 'bindingDelegate' this method receives.
Types of changes
Checklist:
This is to avoid a breaking change in v4, so no need to add an entry to chanelog.