Skip to content

Issue with AsyncLocal execution context when used within a Middleware with dependency injection #13418

@passuied

Description

@passuied

Hi,

We ran into an interesting scenario in one of our middlewares.
We rely on AsyncLocal to expose context data within our application using the ContextAccessor pattern (similar to HttpContextAccessor).

The middleware is capturing information within the request headers and updating the values in the AsyncLocal instance.
The middleware uses dependency injection to resolve the context accessor (that wraps AsyncLocal) and also a Logger object (ILog).

When we added some logic in the DI registration of ILog to resolve an object that has itself a dependency to the Context accessor, it created an abnormal behavior where the values set the AsyncLocal in a request would be kept across subsequent requests!
Beyond the fact that the logic was flawed, as we resolve the context before the middleware ran and set the values, I can't wrap my head around why the values are persisted in AsyncLocal...

I realize this might be complicated to understand all these details so I have recreated the issue in the following repo: https://github.com/passuied/TestAsyncLocalMiddleware

You can find details in README about how to reproduce the issue...

Hope it makes sense!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions