InvalidOperationException: Unable to enable service for type "Microsoft.AspNetCore.Http.IHttpContextAccessor"

I started converting my asp.net RC4 project to RC2 and ran into a problem that IHttpContextAccessor now not resolved.

For simplicity, I created a new ASP.NET RC2 project using the Visual Studio ASP.NET Core Web Application (.Net Framework) template. Then I added a constructor for HomeController, which created a template for me.

 public HomeController(IHttpContextAccessor accessor) { } 

And after starting the application, I get the following error:

InvalidOperationException: Unable to resolve the service for type "Microsoft.AspNetCore.Http.IHttpContextAccessor" when trying to activate "TestNewCore.Controllers.HomeController". at Microsoft.Extensions.Internal.ActivatorUtilities.GetService (IServiceProvider sp, Type Type, Type requiredBy, Boolean isDefaultParameterRequired)

In my real application, I need to enable IHttpContextAccessor in my own service class to access _contextAccessor.HttpContext.Authentication and _contextAccessor.HttpContext.User . It works great in RC1. So how can it be in RC2?

+42
dependency-injection asp.net-core
May 22 '16 at 6:30
source share
1 answer

IHttpContextAccessor is no longer connected by default, you need to register it yourself

 services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
+65
May 22 '16 at 11:08
source
— -



All Articles