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 { getset; }
    }
    public class InstrumentPlayer
    {
        public string PlayerName { getset; }
        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

1 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)