📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Why is IHttpContextAccessor risky in background work, and what should you pass instead?

Junior Theory Intermediate

🎯 Key points

  • AsyncLocal flow, valid only during the request
  • HttpContext objects are pooled and reused, so late reads see null or another request's data
  • HttpContext is not thread-safe: no parallel access even during the request
  • Scoped services captured by background work are disposed at the end of the request scope
  • Copy plain values before starting background work
  • Use Channel<T> + BackgroundService and create a new IServiceScope per work item
  • Keep IHttpContextAccessor out of domain code

⏱ 30-second answer

IHttpContextAccessor stores the current context in an AsyncLocal, so it flows with the request's async calls and is valid only while the request runs. Fire-and-forget work, Task.Run that outlives the request, or a singleton reading it later can see null or a recycled context from another request, because HttpContext objects are pooled. HttpContext is also not thread-safe: reading or writing it from parallel tasks, even during the request, can race and corrupt state. Don't capture scoped services (like a DbContext) either; they are disposed when the request scope ends. Instead, copy the values you need (user ID, correlation ID, tenant) into a message or parameters before starting the work, create a new DI scope in the background worker, and use a queue (Channel<T> with a BackgroundService) for anything that must outlive the request.

🔍 What the interviewer is checking

Checks they understand the request lifetime and AsyncLocal flow

↩ Usually asked after

More in Legacy Technologies

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me