Dependency Injection in ASP.Net MVC using Unity Container

Today, we will learn about injecting Dependency Injection in ASP.Net MVC using Unity Container.
Before going further, we will learn what is Dependency Injection and what is Unity Container.

Dependency Injection is a Software design pattern which we use in C# to reduce class dependency, in other words we can say that it used to increase the loose coupling and makes the code more object oriented.

The Unity Container (Unity) is a lightweight, extensible dependency injection container. As we know, there are many dependency injection containers and unity is one of them.

Steps to implement DI (Dependency Injection) in project are as follows:-

Step 1 – Create a new ASP.Net MVC project

Open the Visual Studio and create a new ASP.Net MVC 4 Empty project as follows-

2017-01-05_1211

Step 2 – Add a new Model class

Add a new model class User.cs in Model folder of the project.

Replace the User.cs model class code with below code-

public class User
 {
 public string Name { get; set; }
 public string Email { get; set; }
 public double RollNumber { get; set; }
 }

Step 3 – Add new interface

Add a new folder IRepository in project and add IUserRepository.cs interface in the folder.

Replace the IUserRepository.cs interface code with below code-

public interface IUserRepository
 {
 IEnumerable<User> GetAll();
 }

Add the namespace of User.cs model class in the above interface file.

Step 4 – Add repository class

Add a new folder Repository in project and add UserRepository.cs class in the folder.

Replace the UserRepository.cs class code with below code-

public class UserRepository : IUserRepository
 {
 private List<User> users = new List<User>();
 public UserRepository()
 {
 users.Add(new User { Name = "Jameer", Email = "jimcute8879@gmail.com", RollNumber = 123456789 });
 users.Add(new User { Name = "Scott", Email = "scott@scott.com", RollNumber = 758735875 });
 users.Add(new User { Name = "Dale", Email = "dale@dale.com", RollNumber = 8967804689 });
 users.Add(new User { Name = "John", Email = "john@jonh.com", RollNumber = 4247437667 });
 }

 public IEnumerable<User> GetAll()
 {
 return users.ToList();
 }
 }

Add the required namespaces for IUserRepository.cs and User.cs model class in the above class file.

Step 5 – Install Unity Container package from Nuget

Run below command to install Unity Container through Nuget Package Manager console.

Install-Package Unity.Mvc4

It will install all the required packages for Unity and will create a Bootstrapper.cs file in the root directory of project.

Now replace the Bootstrapper.cs class file code with below code –

public static class Bootstrapper
 {
 public static IUnityContainer Initialise()
 {
 var container = BuildUnityContainer();

 DependencyResolver.SetResolver(new UnityDependencyResolver(container));

 return container;
 }

 private static IUnityContainer BuildUnityContainer()
 {
 var container = new UnityContainer();

 // register all your components with the container here
 // it is NOT necessary to register your controllers

 // e.g. container.RegisterType<ITestService, TestService>(); 

 //------- Register your Signature and Implementation files here
 container.RegisterType<IUserRepository, UserRepository>(); 
 //--------------------------------

 RegisterTypes(container);

 return container;
 }

 public static void RegisterTypes(IUnityContainer container)
 {

 }

Here you can see that I have registered IUserRepository.cs interface and UserRepository.cs class file.

Step 6 – Create a new Controller

Create a new HomeController.cs controller in the project as below – 

2017-01-05_1254

Replace the HomeController.cs class code with below code-

public class HomeController : Controller
 {
 private readonly IUserRepository _userRepository = null;

 public HomeController(IUserRepository repo)
 {
 this._userRepository = repo;
 }

 public ActionResult Index()
 {
 var data = _userRepository.GetAll();
 return View(data);
 }

 }

Import the required namespaces.

Step 7 – Create a View

Create a new view Index as below – Make the view Strongly Typed with User.cs model class and choose Scaffolding templatesList

2017-01-05_1309

Step 8 – Run the project

You will see the list details as follows – 

2017-01-05_1312

Conclusion

If you put a break point at HomeController constructor, you will see that the Unity has injected the implementation class.

2017-01-05_1314

 

That’s all!!!

Thanks for reading…

Advertisements

8 thoughts on “Dependency Injection in ASP.Net MVC using Unity Container

    1. Thanks for the comments-
      We prefer Dependency Injection because it removes the dependency from the classes. As you can see in my post, it injects the implementation class at run-time and no need to create an instance of class. We can go ahead with interface only.

      The benefit of using Unity Container is that is provides simplified object creation and allows developers to specify dependencies at run-time.

      Like

  1. The benefit of using Unity Container is that is provides simplified object creation and allows developers to specify dependencies at run-time. The benefit of dependency injection is that the project code is testable, maintainable and easy to enhance any new feature in it.

    Like

  2. The benefit of using Unity Container is that is provides simplified object creation and allows developers to specify dependencies at run-time. The benefit of dependency injection is that the project code is testable, maintainable and easy to enhance any new feature in it.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s