1

I am getting an error like this:

Cannot consume scoped service 'Microsoft.AspNetCore.Http.IHttpContextAccessor' from singleton 'MyNamespace.IMyCustomThing'

I am confused, because I register IHttpContextAccessor by calling services.AddHttpContextAccessor(). The code for AddHttpContextAccessor is here. The relevant part is this:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

IHttpContextAccessor is registered as a singleton. Why does ASP.Net Core think it is a scoped service?

NOTE: Incase it is relevant, IMyCustomThing uses the IHttpContextAccessor to see if there is a current HttpContext, if there is not then it takes other actions.

Vaccano
  • 78,325
  • 149
  • 468
  • 850
  • 1
    Which scope's `IHttpContextAccessor` instance should it give to your singleton `IMyCustomThing`? – madreflection Sep 11 '20 at 21:32
  • 1
    @madreflection - That makes it make perfect sense (now). Not sure why the source code shows this registered as a singleton, but it really can't work as one. I could have 10 calls going at once, I would need someway to say which one I mean when I ask for an HttpContext. If the call comes from a singleton, then that is not really possible. – Vaccano Sep 11 '20 at 21:35
  • @madreflection - though looking at this quesiton/answer: https://stackoverflow.com/questions/46330007/why-should-i-inject-ihttpcontextaccessor-as-a-singleton It seems to indicate that it uses an `AsyncLocal` to tell which HttpContext it will return. So it should be able to work as a Singleton. And it registers as one. (I am again confused why it would to that yet through the above error.) – Vaccano Sep 11 '20 at 21:39
  • `AsyncLocal` gets the context, but we're talking about the context *accessor* here. It looks like the context accessor can be registered as a singleton but something is mistakenly registering it as scoped. What happens if you don't call `services.AddHttpContextAccessor()`? Same error (i.e. something else is registering it) or an error about the service not being registered? – madreflection Sep 11 '20 at 21:43
  • 1
    @madreflection - That was it! I found this evil line lurking in a method: `services.AddScoped()`. Once I removed that the error went away! If you want to post as an answer, I will accept. – Vaccano Sep 11 '20 at 22:02

1 Answers1

8

As we sussed out in the comments, you have something registering IHttpContextAccessor as a scoped service. Remove that.

services.AddHttpContextAccessor() registers it as a singleton as it's designed to be used.

madreflection
  • 4,744
  • 3
  • 19
  • 29