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.jsonappsettings.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ách ToDoItem 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:
  1. Request data access services cho mỗi tập options
  2. 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:

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


Tài liệu tham khảo