Skip to main content

Dependency Injection in MVC 5

Here I am going to explain how to implement dependency injection in MVC Project in detail including separate layers for getting data through Services and Repositories.


Steps
Step 1: open visual studio, goto File->New->Project
Open New Project in Visual Studio


Step 2:
Select “Web” from left menu, “ASP.NET Web Application (.NET Framework)” from Project types list and give some name to application (I am giving it as DI).


Step 3:
Select “Empty” template, check MVC Checkbox below and click “OK”
Select Empty Template in MVC

It will take little time to create the solution.
Creating MVC Project

Step 4:
Open Solution Explorer, it will create the folder structure as shown below.
Solution Explorer in Visual Studio

Step 5:
Now we are going to create DAL (Data Access Layer), where data is available, Right Click on Solution Explorer, Goto Add->New Project…
Add New Project in Visual Studio

Step 6:
Select “Windows” from left menu, “Class Library” from Project list, give some name (DAL), click on OK.
Select Class Library in Visual Studio


Step 7:
“Class1.cs” will be opened .
Class1 in Class Library visual studio


Right click on Class1.cs in solution explorer, click “Rename”
Rename Class1 in Class Library visual studio

Rename it as “Customer”, one pop-up will be shown immediately, Click “Yes” (This will rename the file in all places).
Rename Alert message in Visual studio

Step 8:
Now paste the below code in Customer.cs class

namespace DAL
{
    public class Customer
    {
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
        public string City { get; set; }
    }
}

Here we are creating CustomerId, CustomerName and City are the properties of the Customer Class.
Step 9:
Now right click on Solution Explorer, Goto Add->Class…
Add New Class in Visual Studio


Step 10:
Select “Interface”, Name it as “ICustomerRepository.cs”
Add Interface in Visual Studio

Step 11:
Paste the below code in “ICustomerRepository.cs” interface
using System.Collections.Generic;

namespace DAL
{
  public  interface ICustomerRepository
    {
        List<Customer> GetCustomers();
    }
}

Here we have defined one method GetCustomers(), which will return List of Customers with defined properties in Customer.cs file.

Step 11:
Now again right click on Solution Explorer, Goto Add->Class…, Name it as “CustomerRepository.cs”
Add Repository class in visual studio



Step 12:
Paste the below code in “CustomerRepository.cs”
using System.Collections.Generic;

namespace DAL
{
    public class CustomerRepository : ICustomerRepository
    {
        public List<Customer> GetCustomers()
        {
            return new List<Customer>(){
                new Customer { CustomerId = 1, City = "Visakhapatnam", CustomerName = "Tulasi" },
                new Customer { CustomerId = 2, City = "Hyderabad", CustomerName = "Ramana" },
                new Customer { CustomerId = 3, City = "Bangalore", CustomerName = "Bablu" },
                new Customer { CustomerId = 4, City = "Chennai", CustomerName = "Brammaji" },
            };
        }
    }
}

“CustomerRepository.cs” is implementing “ICustomerRepository.cs” interface, since “ICustomerRepository.cs” is having GetCustomers() method, it should be implemented in this class.

For time being I am hardcoding Customer data, in real time we will be calling “dbContext” if using entity framework, Stored procedures for ADO.NET..etc.

Now DAL Layer have completed.

Let’s go and create Service Layer.

Step 13:

In Solution Explorer right click and Add->New Project
Add New Project in Solution Explorer


Step 14:

Select “Windows” from left menu, “Class Library” from Project list, give name as “Services”, click on OK.
Add Services Layer in MVC Project


Step 15:

Now RightClick on Class1.cs->Rename
Rename Class 1 in Solution Explorer.png


Rename it as “ICustomerService”, one pop will be shown immediately click Yes.
Renaming popup in Visual Studio



Step 16:

Now change “Class” to interface, have the same method which is there in “ICustomerRepository.cs” file.

It will ask for reference once we move the cursor to redline and press “ctrl+.”, add the reference by clicking, “using DAL;(from DAL)” option.

How to add references in Visual studio



Step 17:

Paste the below code in ICustomerService.cs

using DAL;
using System.Collections.Generic;

namespace Services
{
    public interface ICustomerService
    {
        List<Customer> GetCustomers();
    }
}

This interface will be having same methods which are defined in DAL interface ie. “ICustomerRepository.cs”


Step 18:

Now again right click on Solution Explorer, Goto Add->Class…, Name it as “CustomerService.cs”
Add Service Class in Visual studio



Step 19:

Paste the below code in “CustomerService.cs”

using System.Collections.Generic;
using DAL;

namespace Services
{
    public class CustomerService : ICustomerService
    {
        private ICustomerRepository _iCustomerRepository;

        public CustomerService(ICustomerRepository iCustomerRepository)
        {
            _iCustomerRepository = iCustomerRepository;
        }
        public List<Customer> GetCustomers()
        {
            return _iCustomerRepository.GetCustomers();
        }
    }
}

Explantaion:

Here “CustomerService.cs” class is implementing “ICustomerService.cs” interface. So actual data is available in “CustomerRepository.cs”, so we should not create object for “CustomerRepository.cs”  and access the GetCustomers method as below.

public List<Customer> GetCustomers()
        {
            CustomerRepository customerRepository = new CustomerRepository();
            return customerRepository.GetCustomers();
        }

This is wrong why because compile time itself, we will know which class object is creating i.e. this violets the dependency injection concept.

We have to inject the interface, runtime whatever class we mapped will be created and call the respective methods by using interface variable.

Here we are injecting interface variable from class constructor. So which class is implementing this interface will be known in only runtime.

public CustomerService(ICustomerRepository iCustomerRepository)

Now DAL and Services layers are ready.

Step 20:

Dependency injection can be implemented by using different frameworks like Ninject, Unity, Autofac, SturctureMap..etc.

Here we are implementing using Unity.

Now Right click on MVC application, Click on  “Manage NuGet Packages...”
Manage NuGet Packages in Visual Studio




Step 21:

NuGet package manager will be opened
NuGet Package Manager


Step 22:

Click on Browse, type “unity.mvc” in search box, select Unity.Mvc5 package.
Unity.MVC5 NuGet Package



Step 23:

Click “Install” button to complete the installation into web project.

Install NuGet Package in MVC Project


One pop up will appear for the package acceptance, click “IAccept”

It will take some time for installation.


Once installation completed it will open readme.txt file.
Unity.MVC5 Readme.txt


Read the file to understand how it works.

Will have to just follow the steps mentioned in this txt file.

Step 24:
Open Global.asax file and paste the below code

using System.Web.Mvc;
using System.Web.Routing;

namespace DI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            UnityConfig.RegisterComponents();
        }
    }
}


We have added the UnityConfig.RegisterComponents(); line.

Step 25:

Open UnityConfig.cs file, which was created at installation time.
UnityConfig.cs



Step 26:

Paste the below code in UnityConfig.cs file

using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Unity.Mvc5;
using DAL;
using Services;

namespace DI
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
var container = new UnityContainer();
         
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            container.RegisterType<ICustomerRepository, CustomerRepository>();
            container.RegisterType<ICustomerService, CustomerService>();
        }
    }
}

Here we have to mention the mappings, which interface will create which class object.

ICustomerRepository will create CustomerRepository object and ICustomerService will create CustomerService object in runtime. So we have mentioned those mappings.

Step 27:
Now Right click on Controller folder Goto Add=>Controller…
Add new Controller


Step 28:

Select MVC 5 Empty Controller, click on Add button
MVC5 Controller - Empty


Step 29:
If you are getting any dll error, just Build the solution once and add the controller
Rename Controller

Name it as “CustomerController”

Step 30:

Paste the below code in CustomerController

using Services;
using System.Web.Mvc;

namespace DI.Controllers
{
    public class CustomerController : Controller
    {
        private ICustomerService _iCustomerService;

        public CustomerController(ICustomerService iCustomerService)
        {
            _iCustomerService = iCustomerService;
        }
     
        public ActionResult GetCustomers()
        {
            return Json(_iCustomerService.GetCustomers(), JsonRequestBehavior.AllowGet);
        }
    }
}

Here we are injecting ICustomerService interface variable from constructor of the controller.

Here we didn’t mention any classname, we are just passing interface variable, So runtime it will call respective class object using mapping which we have done in previous steps.

container.RegisterType<ICustomerService, CustomerService>();

Step 31:
Now run the application and see

http://localhost:63050/customer/GetCustomers

Map the url to “customer/GetCustomers” method, will receive the json result as below
Fiddler webAPI



Step 32:
Now debug the application and see, how it works in background.
Service Layer in WebAPI


_iCustomerService is having Services.CustomerService class object.

Step 33:
Return Json result in MVC Controller


Press F11 when the control is in return statement
Service method in MVC 5



It will hit the GetCustomers method in CustomerService class.

Again Press F11,

Repository method in MVC

It will hit the DAL layer CustomerRepository class method.

So in run time it is creating respective mapped objects .

Download Source Code : Click Here

Comments

Popular posts from this blog

how to integrate kendo ui in asp.net mvc

Introduction: Here I am going to explain how to integrate Kendo to MVC5. I have developed this project by taking reference by this link http://docs.telerik.com/aspnet-mvc/getting-started/asp-net-mvc-5 Before integration, let’s be ready with Kendo UI stuff. Check in your machine, whether “ui-for-asp.net-mvc” installed or not. See the below screen shot If it is not there, then follow the below steps to install it. Step 1: Goto https://www.telerik.com/account/ If you don’t have account, you can create for trail account. Step 2: Paste the below link in browser once you have logged in https://www.telerik.com/download-trial-file/v2/ui-for-asp.net-mvc it will ask download location for software. It looks like below Once after completion of the software, install it. Now we are ready with all the files required for integration of Kendo with MVC. Follow the steps below Step 1: Open visual studio, sele

implement hsts iis

We can implement HSTS using multiple approaches. Approach 1: PRE-REQUISITES: URL Rewrite module has to be installed from the below link https://www.microsoft.com/en-in/download/details.aspx?id=7435 Add the below code to web.config <?xml version= "1.0" encoding= "UTF-8" ?> <configuration>     <system.webServer>         <rewrite>             <rules>                 <rule name = "HTTP to HTTPS redirect" stopProcessing = "true" >                     <match url = "(.*)" />                     <conditions>                         <add input = "{HTTPS}" pattern = "off" ignoreCase = "true" />                     </conditions>                     <action type = "Redirect" url = "https://{HTTP_HOST}/{R:1}"                         redirectType = "Permanent" />