Home > Software engineering >  How do I add a HttpContextAccessor to the Starup.cs in the correct way. (ASP.NET Core 6)
How do I add a HttpContextAccessor to the Starup.cs in the correct way. (ASP.NET Core 6)

Time:09-23

So I'm trying to add a HttpContextAccessor to my startup.cs file and I find these two options.

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddHttpContextAccessor();

So my question is, do I add both of them or just one? And what is the difference between them?

CodePudding user response:

The call to AddHttpContextAccessor uses TryAddSingleton, which will register the service only if it hasn't already been registered.

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

In your example, it has already been registered by that second call to services.AddHttpContextAccessor(), which means the next registration attempts do nothing.
  • Related