ASP.NET Core instantiates the controllers through its built-in dependency injection (DI) framework. Since it fully supports constructor injection, you can have any registered services injected as parameters to your constructor:
//ConfigureServices services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); //HomeController public HomeController(IHttpContextAccessor accessor) { ... }
However, you can also request a service from the DI in a service locator way by leveraging the HttpContext.RequestServices
property as follows:
var accessor = this.HttpContext.RequestServices.GetService<IHttpContextAccessor>();
Note
For the stronglytyped GetService<T>
extension method you need to add a reference to the Microsoft.Extensions.DependencyInjection
namespace.
In action methods, you can also inject a service by decorating its typed parameter with the [FromServices]
attribute as follows:
public IActionResult Index([FromServices] IHttpContextAccessor accessor...