Home > DeveloperSection > Articles > Practical IoC With ASP.NET MVC 4

Practical IoC With ASP.NET MVC 4


ASP.NET MVC C#  ASP.Net  Mvc4 
Ratings:
1 Comment(s)
 2732  View(s)
Rate this:

Practical IoC With ASP.NET MVC 4

Hi everyone in this article I’m explaining about practical ioc with asp.net mvc

Introduction:

At first inversion of control (ioc) is a difficult concept to understand. Even after understanding what is ioc. A developer must the learn apply the concept of ioc and ioc container to a real application in order to use it effectively in this post I’ll learn how to use the unity ioc container in an asp.net mvc4 application to use dependency injection on controllers, filters, view. You will start of by learning the basic of ioc container, how they work and why they important. As well as learning about how internally ASP.NET MVC4 creates controllers and view. In order to understand practically how dependency injection works. In this sample I’ll learn you manually doing dependency injection in ASP.NET MVC4 using your own custom controller factory. After you have done things manually, you’ll see how to add the Microsoft Unity ioc container to your mvc4 application to do dependency injection automatically. Essentially you'll see how it is able to give us more flexibility and reduce the custom code we need to write. John then takes things even further by exploring some advanced dependency injection techniques using Unity to inject views and filters. He’ll also cover some of the advanced features of the Unity IoC container. Finally, you’ll take a tour through some other popular .NET IoC containers and see how to get them working in our ASP.NET MVC 4 application. After taking this course you will be equipped with the skills and knowledge you need to build real applications using Inversion of Control and dependency injection.

As you know, in MVC, Controller depends on Model for data processing or you can say for executing business logic. This article will explain you how can you decouple model layers from the controller layer in an ASP.NET MVC application using Unit DI Container.

Let’s start

Step 1: Open visual studio >> File >> New Project >> ASP.NET MVC 4 Web Application

Give the project name and click ok after click ok open a new window there you select project type.

 

Step 2: Install Unity Container

Now install Unity.Mvc4 Container using Nuget Package console tool as shown below:

PM> Install-Package Unity.Mvc4

 

When it will be installed successfully, you will be find the following two references add to your project and a Bootstrapper.cs class file at project level, as shown below:

 

using System.Web.Mvc;

using Microsoft.Practices.Unity;

using Unity.Mvc4;

 

namespace MvcNUnits

{

  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>();   

      RegisterTypes(container);

 

      return container;

    }

 

    public static void RegisterTypes(IUnityContainer container)

    {

   

    }

  }

}

 

Step 3:  Add new Service Layer

Add a new Folder in the project of the name Repository and add the following interface and a class in this folder:

Product.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace MvcNUnit.Repository

{

    public class Product

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Category { get; set; }

        public decimal Price { get; set; }

    }

}

IProductRepository.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace MvcNUnit.Repository

{

    public interface IProductRepository

    {

        IEnumerable<Product> GetAll();

        Product Get(int id);

        Product Add(Product item);

        bool Update(Product item);

        bool Delete(int id);

    }

}

 

ProductRepository.cs:

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq;

using System.Web;

 

namespace MvcNUnit.Repository

{

    public class ProductRepository : IProductRepository

    {

        private List<Product> products = new List<Product>();

        private int _nextId = 1;

 

        public ProductRepository()

        {

            // Add products for the Demonstration

            Add(new Product { Name = "Computer", Category = "Electronics", Price = 23.54M });

            Add(new Product { Name = "Laptop", Category = "Electronics", Price = 33.75M });

            Add(new Product { Name = "iPhone4", Category = "Phone", Price = 16.99M });

        }

 

        public IEnumerable GetAll()

        {

            // TO DO : Code to get the list of all the records in database

            return products;

        }

        public Product Get(int id)

        {

            // TO DO : Code to find a record in database

            return products.Find(p => p.Id == id);

        }

        public Product Add(Product item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

 

            // TO DO : Code to save record into database

            item.Id = _nextId++;

            products.Add(item);

            return item;

        }

        public bool Update(Product item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

 

            // TO DO : Code to update record into database

            int index = products.FindIndex(p => p.Id == item.Id);

            if (index == -1)

            {

                return false;

            }

            products.RemoveAt(index);

            products.Add(item);

            return true;

        }

        public bool Delete(int id)

        {

            // TO DO : Code to remove the records from database

            products.RemoveAll(p => p.Id == id);

            return true;

        }

    }

}

 

Step 4: Register the dependency in Bootstrapper.cs file

Replace BuildUnityContainer method's content with the following code that registers the ProductRepository Service. You can also register the Product Controller in which we will inject the dependency, but it is optional.

private static IUnityContainer BuildUnityContainer()

    {

      var container = new UnityContainer();

      container.RegisterType<IProductRepository, ProductRepository>();

 

      // register all your components with the container here

      // it is NOT necessary to register your controllers

 

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

      RegisterTypes(container);

 

      return container;

    }

Step 5: Inject Service to controller

Now inject the dependency for the IProductRepository interface using the Product Controller's constructor as shown below:

using MvcNUnit.Repository;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 

namespace MvcNUnit.Controllers

{

    public class ProductController : Controller

    {

        readonly IProductRepository repository;

 

        //inject dependency

        public ProductController(IProductRepository repository)

        {

            this.repository = repository;

        }

 

        public ActionResult Index()

        {

            var data = repository.GetAll();

            return View(data);

        }

 

    }

}

 

Step 6: Setup Dependency injection with Unity in Gloabal.asax.cs

Now, setup the Bootstrapper class with in the Application_Start method so that it can initialize all dependencies. This will be done by calling Initialise() method of the Bootstrapper class as shown below:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace MvcNUnit

{

    // Note: For instructions on enabling IIS6 or IIS7 classic mode,

    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication

    {

        protected void Application_Start()

        {

            AreaRegistration.RegisterAllAreas();

 

            WebApiConfig.Register(GlobalConfiguration.Configuration);

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //BundleConfig.RegisterBundles(BundleTable.Bundles);

            //AuthConfig.RegisterAuth();

 

            //Setup DI

            Bootstrapper.Initialise();

        }

    }

}

 

Now run your application.


Regarding CRUD With IOC

By Jaya kumar on   one year ago
Hi
Kamal

Good one Nice Article.

How to Implemented CRUD Operation using IOC with Form Authentication in MVC4.

Can you share the code for this

Can you share your emailId thats helpful for me

Don't want to miss updates? Please click the below button!

Follow MindStick