View Injection In ASP.NET Core MVC

View injectionis the 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 the View.

Previously, to retrieve the data in View, we needed to 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 helps with injecting the dependencies directly to the View and retrieving the data.

This View displays a list of fruits which are 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 run the app, it will throw an invalid operation exception "No service for type 'MVCCoreExample.Modes.FruitServices' has been registered". This error occurred because we didn't register 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 register your 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 the data from the service injected in View.

Summary

Injecting dependencies directly into MVC View can make things a 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.