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

Viewed 32

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?

1 Answers
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