.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

94

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

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

83

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:

services.AddHttpContextAccessor(); 

This is equivalent to:

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

75

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

63

vote vote

58

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'

Related QUESTION?