Steven Day
Steven Day

Reputation: 343

Using HttpContextAccessor inside of injected class

Using ASP.NET Core 3.0 Preview 5, I'm trying to access HttpContextAccessor from inside an AppState class that I'm injecting into my application.

Unfortunately I keep getting a System.AggregateException with a message of

''Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: [MyNameSpace].AppState Lifetime: Singleton ImplementationType: [MyNameSpace].AppState': Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpContextAccessor' while attempting to activate '[MyNameSpace].AppState'.)'

My Startup.cs file is as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();

    services.AddHttpContextAccessor();
    services.AddSingleton<AppState>();

    // More services
}

and my AppState.cs file is as follows:

private HttpContextAccessor _httpContextAccessor;

public AppState(HttpContextAccessor httpContextAccessor)
{
     _httpContextAccessor = httpContextAccessor;
}

I've checked online and it seems that just adding the AddHttpContextAccessor and AddSingleton<T> to my ConfigureServices method should do the trick but for some reason it isn't working.

As I'm pretty new to ASP.NET Core and Dependency Injection, I just wanted to see if someone who knows what they are doing has any idea what I'm doing wrong!

Upvotes: 3

Views: 3939

Answers (1)

DavidG
DavidG

Reputation: 119186

The AddHttpContextAccessor() method registers the service as a IHttpContextAccessor (note the I prefix to denote it is an interface) and that is what your class needs to explicitly accept in it's constructor:

private IHttpContextAccessor _httpContextAccessor;

public AppState(IHttpContextAccessor httpContextAccessor)
{
     _httpContextAccessor = httpContextAccessor;
}

However, you should not be using this from a singleton class. HTTP requests are, unsurprisingly different per request.

Upvotes: 3

Related Questions