Consuming Services In ASP.NET Core MVC View

In continuation of my previous article on injecting services in controller, this time I am writing on how to inject services directly in MVC View.

In order to achieve this, a new keyword @inject is used. So, let's get started.

  1. Create a new project - Create a new project using ASP.NET Web Application template as in the following:



  2. Add Service Interface - Create an interface named IGUIDService under Services folder as shown below:
    1. public interface IGUIDService  
    2. {  
    3.     string GenerateGUID();  
    4. }  
  3. Add Service Implementation - Create a class named GUIDService under Services folder and provide the implementation of IGUIDService interface as shown below:
    1. public class GUIDService : IGUIDService  
    2. {  
    3.     public string GenerateGUID()  
    4.     {  
    5.         return ("Generated GUID is: " + Guid.NewGuid()).ToString();  
    6.     }  
    7. }  
  4. Add a Controller - The next task is to add a Controller named GUIDController by right clicking on Controllers folder as shown below:

    MVC Controller
     
  5. Add a View - Before adding a View, create a folder under Views folder. Now add a View by right clicking on GUID folder as shown below:

    MVC View Page                                                                                                                                                                                                                                                           Once file is added, inject service inside View as:
    1. @inject IGUIDService guidService  
     Below is the complete code for displaying GUID on View: 
    1. @using CustomTagHelper.Services;  
    2. @inject IGUIDService guidService  
    3.   
    4. <p>@guidService.GenerateGUID()</p>                                                                                                                             
  6. Register Service - The last step is to register the service in the ConfigureServices method of Startup class as shown below:
    1. public void ConfigureServices(IServiceCollection services)  
    2. {  
    3.     ...  
    4.     ...  
    5.     services.AddTransient<IGUIDService,GUIDService>();  
    6. }  
Everything is set. Now run your application and you will be able to see GUID on browser as:



Hope you got an idea on how to inject services in MVC View in ASP.NET Core 1.0.
 
Read more articles on ASP.NET Core:

Up Next
    Ebook Download
    View all
    Learn
    View all