View Injection In ASP.NET Core MVC

View injection is 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.

retrieve

If you're a beginner in ASP.Web Core MVC, look over my earlier article
quick start to configure ASP.Net Core MVC to help configure MVC in ASP.Web Core project.

Setup project 

In Visual Studio, create a new project (File > New > Project), and select ASP.NET Core Web Application (.NET Core).

project

Enter a name for the application and click OK.

Select Web Application to generate the default ASP.NET Core MVC project.(learn quick configure MVC in ASP.NET Core).

Web Application
 
Visual Studio will automatically generate ASP.NET Core MVC project structure and display a welcome screen.

Mvc project Add Services
Add a new folder "Models" and add FruitServices class in it. Now, add a method GetFruits() which returns List<string>().
  1. public class FruitServices  
  2. {  
  3.     public List<string> GetFruits()  
  4.     {  
  5.         return new List<string>() { "Mango""Apple""Apricot""Banana""Grapes" };  
  6.     }  
  7. }  

Inject in View

We can inject a service into a View using the @inject directive. You can think of @inject as adding a property to your View, and populating the property using DI.
 
The basic syntax for View Injection is:
  1. @inject <service> <name>  
  • @inject is the directive used to inject dependencies
  • <service> is service class.
  • <name> is the service injection name by which we can access service methods.
In our example, we are going to inject FruitServices and give service injection name fruitList.
  1. @inject MVCCoreExample.Models.FruitServices fruitList  
  2.   
  3. <h3>Fruit List</h3>  
  4. <ul>  
  5.     @foreach (var name in fruitList.GetFruits())  
  6.     {  
  7.         <li>@name</li>  
  8.     }  
  9. </ul>  
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.

FruitServices
 
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.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     // Add framework services.  
  4.     services.AddMvc();  
  5.     services.AddTransient<FruitServices>();  
  6. }  

Run it!

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

displays data 

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.

Reference
  • http://aspnetmvc.readthedocs.io/projects/mvc/en/latest/views/dependency-injection.html
Image credit: https://learnnutritionwithme.com/tag/diet/