View injection using inject in ASP.NET Core Mvc

View injection is most useful feature introduced in ASP.NET Core. Using ASP.NET Core inbuilt dependency injection container, we can easily inject dependencies in controllers, filters and views. In this post I am going to show how to inject dependencies using inject keyword in view.

Previously, to retrieve data in view we must pass it from the controller using controller properties (like ViewBag, ViewData) or model properties. In ASP.NET Core Mvc things are quite smooth by the usage of Inject directive. Inject will helps to inject dependencies directly to view and retrieve the data.

This view displays a list of fruits which is populated from the injected FruitServices. Using GetFruit() method we can retrieve a list of fruits.

Let's run it without registering FruitServices in DI container.

When we the run app, it will throw an exception "No service
for type 'MVCCoreExample.Modes.FruitServices' has been registered". This error occurred because of we didn't registered FruitServices in a dependency injection container.

Let's register it first and try again!

Register Service

Open startup.cs class and register service for dependency injection in ConfigureServices method. You can registered you own application services using AddTransient method. FruitServices will be instantiated by the container and used to fulfill such requests.

Run it!

Here it is! The sample displays data from service injected in view.

Summary

Injecting dependencies directly into MVC view can make thing bit easier. In this post I have shown a simple View Injection sample to understand the use of Inject directive. View injection can be useful for populating UI elements like selection list, radio buttons etc. This will increase code re-usability and keep your controller clean by minimizing the amount of code required on controllers.