Showing posts with label DI. Show all posts
Showing posts with label DI. Show all posts

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 -
Continue Reading →

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 -
Continue Reading →

Wednesday, 7 January 2015

Dependency Injection

We know that Dependency Injection is software design pattern that allow us to implement loosely couple architecture. The term “loosely couple” carries deep meaning. Before going to discussing of Constructor injection I would like to clarify few important concepts.

What is coupling?
The term coupling represents the relationship between two objects. That means, when two and more object will very much dependent on each other we will say that they are tightly coupled.
Say for example; think about selection process in organization. One has submitted his CV to organization. If his CV gets shortlist then he will get interview call and if he crack interview then we will get offer latter. So, here one process like getting call for interview very much dependent on CV short listing process and getting offer letter process is dependent on his interview process. So, all processes are tightly coupled to each other.
Ok, if we represent this scenario in general manner, process x is dependent on process y and again process y is dependent on process z and in other way process x is dependent on process z that is called transitive dependency.
Couplings are two types in nature

Tight Coupling:- Which is not expected in application in the view point of good design pattern.
Loose Coupling:- Which everyone expects from a good design solution and the entire article is dedicated to implement Loosely Couple architecture.

Why loosely couple ?
Let’s think why not loosely couple. If there is tight coupling among the components then change in one will get effect to another. Think about your desktop computer, If RAM does not work, we pull it and plug another one, if HDD does not work we just replace it, It does not require to change mother board when we change RAM or HDD.
Now, let’s think computer hardware is tightly coupled, and then we would buy a complete new system on change of any parts into it, which would be very expensive.
Same goes true for software architecture and this is the reason why everyone wants to achieve it in project development.
OK, fine we have learned the concept of dependency and the concept of coupling in software architecture. Now let’s come in our main discussion.

What is dependency Injection?
Technically speaking, Dependency Injection is architectural solution to achieve loosely coupled architecture.  It is the process of injecting(converting) coupled (dependent) object into decoupled(independent) object is called Dependency Injection. We can implement Dependency Injection in following ways.

1)Constructor Injection
2)property Injection
3)Interface Injection.

The next point should clear, What Dependency Injection can give in terms of architectural benefit.
As we have discussed Dependency Injection is nothing but a way to loosely coupled architecture, so the value of Dependency Injection is hidden within the benefit of loosely coupled architecture. Here is some of them.
·         We should not think about changing of one component (example of desktop computer) in future.
·         Code will be well maintainable and scalable.
·         Requirement change can able to handle in better ways.
·         Helps in Unit Testing, And many more

Understand Constructor Injection in Dependency Injection.
In this article we will understand only the concept of constructor injection. Before to start with constructor injection we will implement one tight coupled architecture at first and then we will find solution. Here is code implementation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace consoleApp
{
    public class Instrument
    {
        public string InstrumentName { get; set; }
    }
    public class InstrumentPlayer
    {
        public string PlayerName { get; set; }
        public string ReturnInfo(Instrument obj)
        {
            return "Person Name:- "+ PlayerName + " Instrument Naem:- "  + obj.InstrumentName;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Instrument objIns = new Instrument();
            objIns.InstrumentName = "drum";

            InstrumentPlayer objPlayer = new InstrumentPlayer();
            objPlayer.PlayerName = "Sachin Tendulkar";

            Console.WriteLine(objPlayer.ReturnInfo(objIns));

            Console.ReadLine();
        }
    }
}
The output is here.



The problem with this implementation is , We are instantiating Instrument class within InstrumentPlayer class. And we are sending concrete object of Instrument class as a parameter of ReturnInfo() class. Now if the player wants to play another Instrument tomorrow ?
Then we have to define some other instrument class and we have to change the parameter type in  ReturnInfo() function. This is very important part, we have to tune InstrumentPlayer class in additional demand. But if we implement loosely couple architecture, then without touching InstrumentPlayer class we can provide solution. Here is code implementation.

IInstrument.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DITestAppConsole
{
   public interface IInstrument
    {
        string InstrumentName();
    }
}

Program.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DITestAppConsole
{
    #region Drum Class implementing IInstrument interface
    public class Drum : IInstrument
    {
        public string InstrumentName()
        {
            return "Drum";
        }
    }
    #endregion

    #region Guitar class implementing IInstrument interface
    public class Guiter : IInstrument
    {
        public string InstrumentName()
        {
            return "Guiter";
        }
    }
    #endregion

    #region InstrumentPlayer class
    public class InstrumentPlayer
    {
        public string PlayerName { get; set; }
        // in Constructor passing interface object
        public InstrumentPlayer(String Name, IInstrument obj)
        {
            Console.WriteLine("Person Name:- " + Name + " Instrument Name:- " + obj.InstrumentName());
        }
    }
    #endregion

    public class Program
    {
        static void Main(string[] args)
        {
            IInstrument obj1 = new Drum();
            IInstrument obj2 = new Guiter();

            InstrumentPlayer objPlayer = new InstrumentPlayer("Suraj Kumar", obj1);
            objPlayer = new InstrumentPlayer("Suraj Kumar", obj2);
            Console.ReadLine();
        }
    }
}

OutPut:


We have provided solution by introducing the concept of Inheritance in this scenario. Now both class are talking via inherence, Now again if we want to another instrument we will just Implement IInstrument interface to this class and problem will solve.

Download this Project : Click here

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) 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