Pages

Friday, June 24, 2016

What is the meaning of Dependency Injection in programming?


hi everyone 

in this post i will explain the concept of dependency injection in programming 



First What is Dependency Injection ?


Dependency injection mean if your class depend on another class or another external login so you will need to create object of this dependent class to use its logic in your designed class.


for example 

if you want to design laptop class that use another class called electric power that supply your laptop class by power to run 
so you will use electric power object in laptop class (Not Good Design) Like this

class Laptop{
    
    ElectricPower _electricPowerObj;
    
    public Laptop(){

        _electricPowerObj=new ElectricPower();

   }

   Public void Start(){
       //any logic
   }
}

the problems of this designed if you want to change and test and Power source Object you must change constructor method and other variables 

The solution of this problem is using Dependency Injection Design Pattern
that allow you to inject your dependencies as parameters to method and if you want to change dependencies only simply change passed or injected parameter 

interface IPowerSource{

   public void SupplyPower();

}
class ElectricPower : IPowerSource{
   
  public void SupplyPower(){
       
        //any login to supply power
}
class Laptop{
    
    IPowerSource_PowerObj;
    
    public Laptop(IPowerSource power){

        _PowerObj=power;

   }

   Public void Start(){
       //any logic
   }
}
class program {
   public static void main (){
       IPowerSource powersourceObj =new ElectricPower ();
       Laptop laptopObj=new Laptop(powersourceObj );
      laptopObj.Start();
     
   }
}

this model is useful if alter there are another power sources solutions like power source from gas engine .simply you can change laptop power source like 

class ElectricPowerFromEngine : IPowerSource{
   
  public void SupplyPower(){
       
        //any login to supply power
}
class program {
   public static void main (){
       IPowerSource powersourceObj =new ElectricPowerFromEngine ();
       Laptop laptopObj=new Laptop(powersourceObj );
      laptopObj.Start();
     
   }
}

without any changes in laptop class , just inject another object 


Why Dependency Injection?

Dependency Injection is useful because it make your program easy to main and testable 


Inversion of Control?

when you use dependency injection in your program 
this mean you inverse control instead of class hard depend on its dependencies 
no dependencies injected to class 


What is automatic dependency injection ?

there are many tools that make dependency injection automatic 
and enable to create IOC (Inversion of Control) Container to register your all dependencies objects and its resolve in one place 
this tools like Unity , AutoFac 


No comments:

Post a Comment