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

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.

主站蜘蛛池模板: 临邑县| 青岛市| 汕尾市| 信宜市| 贵州省| 信宜市| 白水县| 苍溪县| 九寨沟县| 青河县| 黄冈市| 水城县| 东兴市| 化隆| 紫云| 开阳县| 五寨县| 沙洋县| 吴江市| 临西县| 东方市| 保康县| 神农架林区| 大田县| 灵山县| 农安县| 宿松县| 汽车| 望奎县| 饶平县| 右玉县| 六盘水市| 双柏县| 彰化县| 双牌县| 鄢陵县| 赤峰市| 安庆市| 南平市| 清苑县| 林口县|