官术网_书友最值得收藏!

Dependency injection

ASP.NET Core instantiates the controllers through its built-in 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>();
For the strongly typed 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) { ... }

The next topic covers a very important topic, especially for those that wish to implement multilingual sites.

主站蜘蛛池模板: 渭源县| 普兰店市| 同江市| 蓬溪县| 乌海市| 临海市| 龙游县| 遵义市| 邵阳县| 武义县| 平塘县| 青岛市| 靖宇县| 大荔县| 富顺县| 锡林郭勒盟| 肇东市| 新郑市| 光山县| 视频| 若羌县| 林西县| 孟村| 蚌埠市| 西安市| 黑水县| 榕江县| 株洲县| 北票市| 车险| 荥经县| 大庆市| 英吉沙县| 张掖市| 龙口市| 济源市| 青浦区| 宾阳县| 平凉市| 金昌市| 南部县|