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.

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

Enter a name for the application and click OK. Select Web Application to generate the default ASP.NET Core MVC project.

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

Add Services
Add a new folder "Models" and add FruitServices class in it. Now, add a method GetFruits() which returns List<string>().

    public class FruitServices  
    {  
        public List<string> GetFruits()  
        {  
            return new List<string>() { "Mango", "Apple", "Apricot", "Banana", "Grapes" };  
        }  
    }  


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:
    @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.
    @inject MVCCoreExample.Models.FruitServices fruitList  
      
    <h3>Fruit List</h3>  
    <ul>  
        @foreach (var name in fruitList.GetFruits())  
        {  
            <li>@name</li>  
        }  
    </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.

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.

    public void ConfigureServices(IServiceCollection services)  
    {  
        // Add framework services.  
        services.AddMvc();  
        services.AddTransient<FruitServices>();  
    }  

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

 

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.