Share via


MVC: Dependency Injection Using Unity

An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

Let’s Say we have a classA depends on ClassB.Similarly in MVC controller is dependent on Business class to fetch data.

We shall use interface and try injecting object of Business class in Controller Constructor.

Create a New MVC project i.e MVC Sample and Add To Class library reference project to it.

1) Contracts-here we shall have our interfaces

2)BAL - We shall write business logic here:

We shall now implements DI by implementing a class is inherited by an interface.

Go to Contracts add an Interface IPerson

using Models;
 
using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Text;
 
using System.Threading.Tasks;
 
namespace Contracts
 
{
 
    public interface  IPerson
 
    {
 
        string getPerson(string id);
 
    }
 
}
 
Here we have an interface  with method getperson that will implemented by class Person in BAL
 
using Contracts;
 
using Models;
 
using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Text;
 
using System.Threading.Tasks;
 
namespace BAL
 
{
 
    public class  Person : IPerson
 
    {
 
        public string  getPerson(string  id)
 
        {
 
            return "Pradeep Varma,Employee ID"  + id;
 
        }
 
    }
 
}

Now in WebAPP MVCSample create a controller Home and Inject the interface in controller constructor.

using Contracts;
 
using Models;
 
using MVCSample.Controllers.Filters;
 
using MVCSample.Models;
 
using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Threading.Tasks;
 
using System.Web;
 
using System.Web.Mvc;
 
using System.Web.Security;
 
using Kendo.Mvc.UI;
 
using Kendo.Mvc.Extensions;
 
namespace MVCSample.Controllers
 
{
 
    public class  HomeController : Controller
 
    {
 
        //
 
        // GET: /Home/
 
        private readonly  IPerson obj;
 
        public HomeController(IPerson _obj)
 
        {
 
            obj = _obj;
 
        }
 
  
 
        public ActionResult Home()
 
        {
 
            ViewBag.Message = obj.getPerson("7");
 
           
 
        }
 
    }
 
}

Run the Application

You will get the Error when you try to access Home controller Home Action Result.

The Error has occurred because the Interface doesn't to know how to construct the class Person.

So, this problem can be solved using a Dependency Injection Container.

Now we need to install Unity which will be our Dependency Injection Container.

Go To WebAPP right click on it use NugetPackage and install Unity.

After installing it we observe that we have a class called Bootstrapper.cs where we shall resolve dependency.

In Bootstrapper.cs add container.RegisterType<IPerson, Person>(); in Intialise()

using System.Web.Mvc;
 
using Microsoft.Practices.Unity;
 
using Unity.Mvc4;
 
using MVCSample.Controllers;
 
using Contracts;
 
using BAL;
 
namespace MVCSample
 
{
 
  public static  class Bootstrapper
 
  {
 
    public static  IUnityContainer Initialise()
 
    {
 
      var container = BuildUnityContainer();
 
             container.RegisterType<IPerson, Person>();
 
      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)
 
    {
 
    
 
    }
 
  }
 
}

Now we need Initialise in Global.asax.cs

using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Web;
 
using System.Web.Http;
 
using System.Web.Mvc;
 
using System.Web.Optimization;
 
using System.Web.Routing;
 
namespace MVCSample
 
{
 
    // 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);
 
            Bootstrapper.Initialise();
 
           
 
        }
 
    }
 
}

Run the application

Home.cshtml

@{

    ViewBag.Title = "Home";

}

<h1>@ViewBag.Message</h1>

The Output will be