How To Implement Dependency Injection In MVC Project

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

Step 1

Open Visual Studio, go to File->New->Project.

MVC

Step 2

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

MVC

Step 3

Select “Empty” template, check MVC Checkbox below, and click “OK”.

MVC

It will take a little time to create the solution.

MVC

Step 4

Open Solution Explorer, it will create the folder structure as shown below.

MVC

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…

MVC

Step 6

Select “Windows” from the left menu, “Class Library” from Project list, give some name (DAL), and click OK.

MVC

Step 7

“Class1.cs” will be opened.

MVC

Right click on Class1.cs in Solution Explorer and click “Rename”.

MVC

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

MVC

Step 8

Now, paste the below code in Customer.cs class.

  1. namespace DAL  
  2. {  
  3.     public class Customer  
  4.     {  
  5.         public int CustomerId { get; set; }  
  6.         public string CustomerName { get; set; }  
  7.         public string City { get; set; }  
  8.     }  
  9. }  

Here, we are creating CustomerId, CustomerName and City, the properties of the Customer Class.

Step 9

Now, right click on Solution Explorer, Go to Add->Class…

MVC

Step 10

Select “Interface”, Name it as “ICustomerRepository.cs”.

MVC

Step 11

Paste the below code in “ICustomerRepository.cs” interface.

  1. using System.Collections.Generic;  
  2.   
  3. namespace DAL  
  4. {  
  5.   public  interface ICustomerRepository  
  6.     {  
  7.         List<Customer> GetCustomers();  
  8.     }  
  9. }  

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

Step 11

Now again, right click on Solution Explorer, Go to Add->Class…, Name it as “CustomerRepository.cs”.

MVC

Step 12

Paste the below code in “CustomerRepository.cs”.

  1. using System.Collections.Generic;  
  2.   
  3. namespace DAL  
  4. {  
  5.     public class CustomerRepository : ICustomerRepository  
  6.     {  
  7.         public List<Customer> GetCustomers()  
  8.         {  
  9.             return new List<Customer>(){  
  10.                 new Customer { CustomerId = 1, City = "Visakhapatnam", CustomerName = "Tulasi" },  
  11.                 new Customer { CustomerId = 2, City = "Hyderabad", CustomerName = "Ramana" },  
  12.                 new Customer { CustomerId = 3, City = "Bangalore", CustomerName = "Bablu" },  
  13.                 new Customer { CustomerId = 4, City = "Chennai", CustomerName = "Brammaji" },  
  14.             };  
  15.         }  
  16.     }  
  17. }  

“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 has completed.

Let’s go and create Service Layer.

Step 13

In Solution Explorer, right-click and Add->New Project.

MVC

Step 14

Select “Windows” from the left menu, “Class Library” from Project list, give a name as “Services”, click on OK.

MVC

Step 15

Now, Right-click on Class1.cs->Rename.

MVC

Rename it as “ICustomerService”, one pop will be shown immediately. Click Yes.

MVC

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.

MVC

Step 17

Paste the below code in ICustomerService.cs

  1. using DAL;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace Services  
  5. {  
  6.     public interface ICustomerService  
  7.     {  
  8.         List<Customer> GetCustomers();  
  9.     }  
  10. }  

This interface has the 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”

MVC

Step 19

Paste the below code in “CustomerService.cs”

  1. using System.Collections.Generic;  
  2. using DAL;  
  3.   
  4. namespace Services  
  5. {  
  6.     public class CustomerService : ICustomerService  
  7.     {  
  8.         private ICustomerRepository _iCustomerRepository;  
  9.   
  10.         public CustomerService(ICustomerRepository iCustomerRepository)  
  11.         {  
  12.             _iCustomerRepository = iCustomerRepository;  
  13.         }  
  14.         public List<Customer> GetCustomers()  
  15.         {  
  16.             return _iCustomerRepository.GetCustomers();  
  17.         }  
  18.     }  
  19. }  

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.

  1. public List<Customer> GetCustomers()  
  2.         {  
  3.             CustomerRepository customerRepository = new CustomerRepository();  
  4.             return customerRepository.GetCustomers();  
  5.         }  

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

We have to inject the interface, runtime and 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 only  inruntime.

  1. 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...”

MVC

Step 21

NuGet package manager will be opened

MVC

Step 22

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

MVC

Step 23

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

MVC

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

It will take some time for installation.

MVC

Once the installation is completed, it will open the readme.txt file.

MVC

Read the file to understand how it works.

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

Step 24

Open Global.asax file and paste the below code.

  1. using System.Web.Mvc;  
  2. using System.Web.Routing;  
  3.   
  4. namespace DI  
  5. {  
  6.     public class MvcApplication : System.Web.HttpApplication  
  7.     {  
  8.         protected void Application_Start()  
  9.         {  
  10.             AreaRegistration.RegisterAllAreas();  
  11.             RouteConfig.RegisterRoutes(RouteTable.Routes);  
  12.             UnityConfig.RegisterComponents();  
  13.         }  
  14.     }  
  15. }  

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

Step 25

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

MVC

Step 26

Paste the below code in UnityConfig.cs file.

  1. using System.Web.Mvc;  
  2. using Microsoft.Practices.Unity;  
  3. using Unity.Mvc5;  
  4. using DAL;  
  5. using Services;  
  6.   
  7. namespace DI  
  8. {  
  9.     public static class UnityConfig  
  10.     {  
  11.         public static void RegisterComponents()  
  12.         {  
  13.             var container = new UnityContainer();  
  14.               
  15.             DependencyResolver.SetResolver(new UnityDependencyResolver(container));  
  16.             container.RegisterType<ICustomerRepository, CustomerRepository>();  
  17.             container.RegisterType<ICustomerService, CustomerService>();  
  18.         }  
  19.     }  
  20. }  

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

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

Step 27

Now Right click on Controller folder Goto Add=>Controller…

MVC

Step 28 

Select MVC 5 Empty Controller, click on Add button

MVC

Step 29

If you are getting any dll error, just build the solution once and add the controller.

MVC

Name it as “CustomerController”

Step 30

Paste the below code in CustomerController

  1. using Services;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace DI.Controllers  
  5. {  
  6.     public class CustomerController : Controller  
  7.     {  
  8.         private ICustomerService _iCustomerService;  
  9.   
  10.         public CustomerController(ICustomerService iCustomerService)  
  11.         {  
  12.             _iCustomerService = iCustomerService;  
  13.         }  
  14.           
  15.         public ActionResult GetCustomers()  
  16.         {  
  17.             return Json(_iCustomerService.GetCustomers(), JsonRequestBehavior.AllowGet);  
  18.         }  
  19.     }  
  20. }  

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 at runtime, it will call respective class object using mapping which we have done in previous steps.

  1. container.RegisterType<ICustomerService, CustomerService>();  

Step 31

Now, run the application and see -

http://localhost:63050/customer/GetCustomers

Map theURLl to “customer/GetCustomers” method, will receive the JSON result as below.

MVC

Step 32

Now, debug the application and see how it works in background.

MVC

_iCustomerService is having Services.CustomerService class object.

Step 33

MVC

Press F11 when the control is in return statement.

MVC

It will hit the GetCustomers method in CustomerService class.

Again, press F11.

MVC

It will hit the DAL layer CustomerRepository class method.

So, in runtime, it is creating respective mapped objects to interface variables.


Similar Articles