CodexBloom - Programming Q&A Platform

C# 10 and .NET 6: Issues with using AsyncLocal for scoped dependency injection in a web API

👀 Views: 53 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-04
c# .net-6 asynchronous dependency-injection C#

I'm having trouble with Does anyone know how to Quick question that's been bugging me - I'm encountering unexpected behavior when attempting to use `AsyncLocal<T>` for scoped dependency injection in my .NET 6 Web API application. Specifically, when I use an `AsyncLocal<T>` to store a user context object that's set in the middleware, it seems to lose its value when accessed in the controller actions, leading to a `NullReferenceException`. Here's a simplified version of my code: ```csharp public class UserContext { public string UserId { get; set; } } public class UserContextMiddleware { private static readonly AsyncLocal<UserContext> _current = new AsyncLocal<UserContext>(); public async Task InvokeAsync(HttpContext context, RequestDelegate next) { _current.Value = new UserContext { UserId = "12345" }; await next(context); } public static UserContext Current => _current.Value; } public class MyController : ControllerBase { [HttpGet] public IActionResult GetUser() { var userContext = UserContextMiddleware.Current; if (userContext == null) { return NotFound("User context is null"); } return Ok(userContext.UserId); } } ``` I set up the middleware in `Startup.cs` like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<UserContextMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` When I hit the endpoint, the value of `UserContext.Current` is always null. I've verified that the middleware is correctly invoked before the controller action. I even tried wrapping the user context retrieval in a try-catch to see if there are any exceptions, but it only throws a `NullReferenceException`. I've also checked my project for any asynchronous execution issues. Is there something I might be missing with the `AsyncLocal` usage, or is this a limitation when working with dependency injection in ASP.NET Core? How can I ensure that my scoped data persists across asynchronous boundaries? I'm working on a CLI tool that needs to handle this. Any ideas what could be causing this? Am I missing something obvious? This is for a CLI tool running on Linux. Any ideas how to fix this?