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

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives