Dependency Injection vào Views là gì?
ASP.NET Core hỗ trợ dependency injection (DI) vào views. Điều này hữu ích cho các view-specific services như localization hoặc data chỉ dùng để populate view elements.
Lưu ý: Hầu hết data mà views hiển thị nên được truyền từ controller. @inject chỉ nên dùng cho view-specific services.
Configuration Injection
Inject Configuration vào View
Giá trị từ settings files nhưappsettings.json và appsettings.Development.json có thể được inject vào view.
appsettings.Development.json
MVC View
Service Injection với @inject
Cú pháp
Sử dụng directive@inject để inject service vào view:
Ví dụ: ToDo List với Statistics
View này hiển thị danh sáchToDoItem cùng với statistics summary từ injected StatisticsService:
Đăng ký Service trong Program.cs
StatisticsService Implementation
Populating Lookup Data
Vấn đề truyền thống
Rendering form với dropdown lists thường yêu cầu controller:- Request data access services cho mỗi tập options
- Populate model hoặc ViewBag với các options
Giải pháp: Inject Service vào View
ProfileOptionsService
Lưu ý: Unregistered type sẽ throw exception tại runtime vì service provider được query nội bộ qua GetRequiredService.
Overriding Services
Default Fields có sẵn
View có sẵn các default fields:| Field | Mô tả |
|---|---|
Html | HTML Helpers |
Component | View Components |
Url | URL Helpers |
Override Html Helper
Sử dụng@inject để override default HTML Helpers với phiên bản custom:
So sánh: Controller DI vs View DI
| Tiêu chí | Controller DI | View DI (@inject) |
|---|---|---|
| Mục đích | Business logic, data access | View-specific services |
| Cú pháp | Constructor injection | @inject directive |
| Testability | Cao | Thấp hơn |
| Khuyến nghị | ✅ Ưu tiên dùng | Hạn chế, chỉ khi cần |