.net - InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

ID : 20368

viewed : 42

Tags : .netdependency-injectionasp.net-core.net

Top 5 Answer for .net - InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'

vote vote


IHttpContextAccessor is no longer wired up by default, you have to register it yourself

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
vote vote


As of .NET Core 2.1 there is an extension method that has been added to correctly register an IHttpContextAccessor as a singleton. See Add helper to register IHttpContextAccessor #947. Simply add as follows in your ConfigureServices() method:


This is equivalent to:

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
vote vote


services.AddScoped(sp => sp.GetService<IHttpContextAccessor>().HttpContext.Session); 
vote vote


vote vote


Create Globals class in app/globals.ts:

import { Injectable } from '@angular/core';  Injectable() export class Globals{     VAR1 = 'value1';     VAR2 = 'value2'; } 

In your component:

import { Globals } from './globals';  @Component({     selector: 'my-app',     providers: [ Globals ],     template: `<h1>My Component {{globals.VAR1}}<h1/>` }) export class AppComponent {     constructor(private globals: Globals){     } } 

Note: You can add Globals service provider directly to the module instead of the component, and you will not need to add as a provider to every component in that module.

@NgModule({     imports: [...],     declarations: [...],     providers: [ Globals ],     bootstrap: [ AppComponent ] }) export class AppModule { } 

Top 3 video Explaining .net - InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Http.IHttpContextAccessor'