Wednesday, 18 February 2015

DI - ASP.NET MVC 4 using Unity

In my previous post I have already Described about DI and IOC [Click here]. Here in this Post I'll Describe How to Implement DI using Unity Container in  MVC4.

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.

Step 1- First step is to create a new Asp.Net MVC4 Project.

Step 2- Install Unity Container
Now install Unity.Mvc4 Container using NuGet Package Manager Console tool as shown below:


You can also do online search for Unity.Mvc4 Container by navigating to Tools=>Extension and Update..=>Online options in Visual Studio 2012 or 2010SP1 and install it.

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:



  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- For demonstrating dependency injection we need some sort of interfaces and their concrete implementations, so in that regard I will add a new interface named IMessageService and it’s
implementation MessageService in the Model folder to the project root.

Here is the interface IMessageService:

    public interface IMessageService
    {
        string GetMessage();
    }

and MessageService:
  public class MessageService :IMessageService
    {
        public string GetMessage()
        {
           return "Hello World!";
        }

    }
Step 4- Register the Dependency in Bootstrapper.cs file
Replace BuildUnityContainer method's content with the following code that registers the MessageService Service. You can also register the HomeController in which we will inject the dependency, but it is optional.

    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>(); 
      container.RegisterType<IMessageService, MessageService>();
      RegisterTypes(container);

      return container;

    }

Step 5- Inject Service to Controller
Now inject the dependency for the IMessageService interface using the HomeController's constructor as shown below:

   public class HomeController : Controller
    {
        private readonly IMessageService _messageService;
        public HomeController(IMessageService messageservice)
        {
            this._messageService = messageservice;
        }

        public ActionResult Index()
        {
            ViewBag.Message = _messageService.GetMessage();

            return View();
        }
    }

Index.cshtml
<h2>@ViewBag.Message</h2>

Step 6 – Setup Dependency Injection with Unity in Global.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:

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

Step 7- Run the Application and see how it works.


It's all Done.

I hope you enjoyed with DI.

Download the Complete Project here Click me -

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)