- Modern Web Development with ASP.NET Core 3
- Ricardo Peres
- 127字
- 2021-06-18 18:36:02
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.
推薦閱讀
- 玩轉Scratch少兒趣味編程
- LabVIEW Graphical Programming Cookbook
- 潮流:UI設計必修課
- Data Analysis with IBM SPSS Statistics
- Learning Neo4j 3.x(Second Edition)
- Rust Essentials(Second Edition)
- Getting Started with Gulp
- Integrating Facebook iOS SDK with Your Application
- Learning Continuous Integration with TeamCity
- Learning Ionic
- Mastering VMware Horizon 7(Second Edition)
- Android移動應用項目化教程
- Arduino機器人系統(tǒng)設計及開發(fā)
- 現(xiàn)代CPU性能分析與優(yōu)化
- Python機器學習與量化投資