Sunday, 15 February 2015

DI - ASP.NET MVC 4 using Ninject

Dependency Injection is an implementation of the Inversion of Control pattern.  There are two possible implementations for IoC:
  1. Service Locator
  2. Dependency Injection
I've already discussed about What is DI and How to Use it Click here to Read about DI . here, in this Post I am Going to Use DI using NInject Container.
There are lots of IoC containers available:
  1. Unity
  2. CastleWindsor
  3. StructureMap
  4. Spring.NET
  5. Ninject
  6. Autofac 
At runtime, they take care of the responsibility of passing in the correct type. Many of them are open source or freely available.

NInject- Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

Let’s start

Create a new Mvc 4 Project.
Add NInject from Manage Nuget Package Reference.

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 India Won the Match.";
        }

    }

Add a new class in Model name NInjectDependencyResolver that implements IDependencyResolver Interface and Implements it's two functions object GetService(Type serviceType) and IEnumerable<object> GetServices(Type serviceType) for DI work, so It can be implement like this:

using Ninject;
using Ninject.Syntax;
    public class NInjectDependencyResolver : IDependencyResolver
    {
        private readonly IResolutionRoot _resolutionRoot;

        public NInjectDependencyResolver(IResolutionRoot kernel)
        {
            _resolutionRoot = kernel;
        }

        public object GetService(Type serviceType)
        {
            return _resolutionRoot.TryGet(serviceType);
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return _resolutionRoot.GetAll(serviceType);
        }

        public static void setUpDependencyInjection()
        {
            //Create NInject DI Kernel
            IKernel kernel = new StandardKernel();

            //Register Services with NInject DI Container
            kernel.Bind<IMessageService>().To<MessageService>();

            //Tell ASP.Net MVC to use our NInject DI COntainer
            DependencyResolver.SetResolver(new NInjectDependencyResolver(kernel));
        }
    }

ok, in the method above setUpDependencyInjection() I created a standard kernel which is implemented in the Ninject.dll and bind our service to it’s concrete implementation, say whenever the application encounters the IMessageService then it will automatically creates a new instance of MessageService damn simple isn’t it, don’t forget to call above method in Application_Start().

Now in the Application_Start(),  hook DI related stuff. Call setUpDependencyInjection function in Application_Start() Function.

        protected void Application_Start()
        {
          ......
          ...

           NInjectDependencyResolver.setUpDependencyInjection();
        }

To test it, open up HomeController and change it like that:

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

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

First, I add a private readonly field _messageService that holds our service instance on the fly. I also add a class constructor which takes single parameter of type IMessageService and then set it to our private field.
In Index() ActionResult method I called the GetMessage() and we are done, look I didn’t create a new instance of MessageService class anywhere it will automatically created by our DI container.

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

Now Run the Application and see the output :


you see the message above it comes from our MessageService class’s GetMessage() method which I called in HomeController.

The advantages of using Dependency Injection pattern and Inversion of Control are the following:

  1. Reduces class coupling
  2. Increases code reusing
  3. Improves code maintainability
  4. Improves application testing
Hope you understand how DI works in ASP.NET MVC 4 with Ninject.

Download the Complete Project here Click me -
Read More about NInject on Codeplex Click me -

1 comment:

  1. To Install NInject go to package manager console and type
    Install-Package Ninject -Version 3.2.2
    And Hit Enter

    ReplyDelete

Topics

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

Dotnet Guru Archives