0

I have builder.Services.AddHttpContextAccessor(); in my program.cs

but keep getting the following error when I try to run the app

Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpContextAccessor' while attempting to activate

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Robw
  • 39
  • 1
  • 3
  • 1
    I believe you need to use `IHttpContextAccessor` to resolve in constructors / properties, not the concrete class type. – Haney Aug 16 '23 at 15:35

2 Answers2

0

https://stackoverflow.com/a/75520898/5290908

For .NET Core 7.0, add the following code in the Program.cs class:

builder.Services.AddHttpContextAccessor();

This is equivalent to:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Rahadur
  • 109
  • 1
  • 11
  • Have tried both suggestions, with the same error – Robw Aug 16 '23 at 16:05
  • @Robw I have just created a .NET 7 project and added `builder.Services.AddHttpContextAccessor();` It works like a charm with no issue. Can you please tell me what is your current development framework and environment? – Rahadur Aug 16 '23 at 16:12
  • Thanks for your help. I've figured it out. The consturctor was using HttpContextAccessor instead of IHttpContextAccessor. DOH – Robw Aug 16 '23 at 16:48
  • Please don't answer with a link to another answer. Instead, once you have enough rep, flag the question as a duplicate. – Heretic Monkey Aug 16 '23 at 18:07
0

Thanks for your help. I've figured it out. The consturctor was using HttpContextAccessor instead of IHttpContextAccessor.

Robw
  • 39
  • 1
  • 3