Why is it dangerous to capture and store an HttpContext reference in a singleton-scoped service, and what should you use instead?
Short answer
HttpContext is only valid for the duration of a single request and is reused/recycled by the framework after the request completes -- storing a reference to it in a singleton service can lead to accessing stale, disposed, or cross-request-contaminated data, especially under…
Advertisement
AModel answer
HttpContext is only valid for the duration of a single request and is reused/recycled by the framework after the request completes -- storing a reference to it in a singleton service can lead to accessing stale, disposed, or cross-request-contaminated data, especially under concurrent load where multiple requests might interleave. The recommended alternative is injecting IHttpContextAccessor, which correctly retrieves the current request's HttpContext via AsyncLocal-based ambient state, though even that should be used judiciously since it introduces implicit dependencies.
// Dangerous: DON'T do this
public class BadSingletonService {
private HttpContext _context; // captured once, becomes stale/wrong across requests
}
// Correct approach
public class GoodService {
private readonly IHttpContextAccessor _accessor;
public GoodService(IHttpContextAccessor accessor) => _accessor = accessor;
public string GetCurrentUserId() => _accessor.HttpContext?.User?.Identity?.Name;
}Real-world example
A subtle production bug where one user occasionally sees another user's data traced back to a singleton service that had incorrectly cached a reference to an early request's HttpContext instead of using IHttpContextAccessor.
Likely follow-ups
- How does IHttpContextAccessor use AsyncLocal to track the ambient context?
- Why do many architects still recommend avoiding IHttpContextAccessor when possible?
Related topics