Dependency Injection in ASP.NET MVC 6 Views

Posted by: Mahesh Sabnis , on 10/31/2016, in Category ASP.NET MVC
Views: 48290
Abstract: Dependency Injection in ASP.NET MVC 6 a.k.a ASP.NET Core MVC Views helps developers to access view specific service logic directly used in View, without adding explicit logic in the controller.

ASP.NET Core MVC previously known as MVC 6 is a rich model view controller framework with several new features that make developing web apps, much easier as compared to the previous releases. One of the features of this release is an inbuilt support for Dependency Injection.

I have already published an article on the Dependency Injection in ASP.NET MVC 6.


Dependency Injection in Views

In MVC, Views are the final facilitator for displaying data to the end-user. We need to define Models based on the type of data representation. Sometimes we get a requirement that along with a collection of the data to be displayed on the view, we also need to display a summary of the data, e.g. In the Index view for showing a list of employees, we also need to display the count of managers, leads and clerks on the view, say at the bottom of the index page. This usually leads to defining logic on the View which in turn may increase development and maintenance cost.

The Dependency Inject in Views feature of ASP.NET MVC 6 can prove helpful here to access view specific service logic directly used in View, without adding explicit logic in the controller.

In the following steps, we will see how to implement our requirement.

Note: For this application we need Visual Studio 2015 and ASP.NET Core. Download the Visual Studio 2015 Community Edition. Also get ASP.NET Core.

Step 1: Open Visual Studio 2015 and create a new ASP.NET Core application of shown in the following image. Name this application as MVC6_ViewDependencyInjection.


Note here we are selecting the ASP.NET Core Web Application template. Click on OK button, the Select Template Window will be displayed, select Web Application from it as shown in the following image


This will create a project which contains Controllers, Views and the wwwroot folder.

Step 2: In the project, add a new folder named Models. In this folder add a new class file as shown in the following image. Name this class file as ModelClasses.cs


Step 3: Add the following code in this file

using System.Collections.Generic;

namespace MVC6_ViewDependencyInjection.Models
    public class Employee
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public int Salary { get; set; }
        public string Designation { get; set; }

    public class EmployeeDatabase : List< Employee >
        public EmployeeDatabase()
            Add(new Employee() { EmpNo = 101, EmpName = "Ajay", Salary = 50000, Designation = "Manager" });
            Add(new Employee() { EmpNo = 102, EmpName = "Akash", Salary = 20000, Designation = "Lead" });
            Add(new Employee() { EmpNo = 103, EmpName = "Brijesh", Salary = 45000, Designation = "Clerk" });
            Add(new Employee() { EmpNo = 104, EmpName = "Bhairav", Salary = 23000, Designation = "Manager" });
            Add(new Employee() { EmpNo = 105, EmpName = "Chinmay", Salary = 13000, Designation = "Lead" });
            Add(new Employee() { EmpNo = 106, EmpName = "Chaitanya", Salary = 56000, Designation = "Clerk" });
            Add(new Employee() { EmpNo = 107, EmpName = "Deepak", Salary = 76000, Designation = "Manager" });
            Add(new Employee() { EmpNo = 108, EmpName = "Dinesh", Salary = 29000, Designation = "Lead" });
            Add(new Employee() { EmpNo = 109, EmpName = "Eshwar", Salary = 98000, Designation = "Clerk" });
            Add(new Employee() { EmpNo = 110, EmpName = "Eknath", Salary = 23000, Designation = "Manager" });

The above code contains an Employee class with properties of Employee and an EmployeeDatabase class which is derived from List. This contains records for Employee. (Note: alternatively EntityFramework can also be used here.)

Step 4: In the project, add a new folder named Services. Similar to the previous step, add a new class file in this folder called DatService.cs. Add the following code in this file

using System.Collections.Generic;
using System.Linq;

using MVC6_ViewDependencyInjection.Models;

namespace MVC6_ViewDependencyInjection.Services
    public class DalService
        EmployeeDatabase db;

        public DalService()
            db = new EmployeeDatabase();  

        public IEnumerable< Employee > Get()
            return db;

        public int GetManagerCount()
            var Res = (from e in db
                       where e.Designation == "Manager"
                       select e);
            return Res.Count();
        public int GetLeadCount()
            var Res = (from e in db
                       where e.Designation == "Lead"
                       select e);
            return Res.Count();
        public int GetClerkCount()
            var Res = (from e in db
                       where e.Designation == "Clerk"
                       select e);
            return Res.Count();

The above code uses an EmployeeDatabase class to access data from it. The DalService class contains methods for reading all employees (Get method) and methods for returning Manager, Lead and Clerk count.

Step 5: Since we will be registering the DalService in the default Dependency Injection provided in MVC 6, we will use the IServiceCollection interface to register the DalService. Open Startup.cs file and add the following code in the ConimageService() method

public void ConimageServices(IServiceCollection services)
    services.AddTransient< dalservice >();     ….. 

Step 6: In the Controllers folder, add a new MVC Controller class of name EmployeeController as shown in the following image



In this Controller class add the following code

using Microsoft.AspNetCore.Mvc;
using MVC6_ViewDependencyInjection.Services;
namespace MVC6_ViewDependencyInjection.Controllers
    public class EmployeeController : Controller

        DalService dService;

        public EmployeeController(DalService s)
            dService = s;

        // GET: /< controller >/
        public IActionResult Index()
            var data = dService.Get();
            return View(data);

We are using Constructor Injection to inject the DalService in the EmployeeController and to access its methods.

Step 7: In the Views folder add a new Subfolder of name Employee and in this folder add a new MVC View Page of name Index.cshtml as shown in the following image


In this image add the following markup and declaration

@using System.Collections.Generic
@using MVC6_ViewDependencyInjection.Services;
@model IEnumerable< MVC6_ViewDependencyInjection.Models.Employee>
@inject DalService dService

< h1>List of Employees
< table class="table table-bordered table-condensed table-striped">
    @foreach (var emp in Model)

< hr />
< h3>Total No. of Managers : @dService.GetManagerCount()

< h3>Total No. of Leads : @dService.GetLeadCount()
< h3>Total No. of Clerks : @dService.GetClerkCount()

The view uses Generic and Services namespaces. This view is set to IEnumerable as a Model for the View. Using @inject, the DalService is injected into the view. We can now access methods of the service using the dService object declared using @inject. The view can now access GetManagerCount(), GetLeadCount(), GetClerkCount() methods of the service.

Run the Application by making the following changes in the Configure() method of the Startup class

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

    app.UseMvc(routes =>
            name: "default",
            template: "{controller=Employee}/{action=Index}/{id?}");

We are changing the route template default values to Employee controller. After running the application, the view will show count of Managers, Clerks and Leads as seen in the following image



Dependency Injection in Views in MVC 6 helps developers to access view specific service logic directly used in View, without adding explicit logic in the controller.

Download the entire source code of this article over here (Github)

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!