In this page u will reach what the dependency injection is and why we use that.
Loosely Coupled
It means classes which is contained with the others should be loosely coupled.Furthermore,if developer wants to change anything in his codes,he can easly change thanks to loosely coupled if they were storngly coupled,he should write every properties of that class again,totally spending time ineffiecently.
Dependency Injection
That's why Dependency injection is used for application which may need some changing one day.Dependency injection can apply with 2 ways;
Constructor Injection(Constructor Based Dependecy Injection)
Setter Injection(Setter Based Dependency Injection)
Constructor Based Dependency Injection
class Car
{
public void Start()
{
//...
}
public void Break()
{
//...
}
public void TurnRight()
{
//...
}
public void TurnLeft()
{
//..
}
}
class Vehicle
{
Car car;
public Vehicle()
{
car= new car(); //Constructur*
}
public void UseCar()
{
araba.Start();
araba.TurnRight();
araba.Stop();
araba.TurnLeft();
}
}
For this example let's think about the scenario,we want to create a "bus" for vehicle class.Of course we will change everyting.Now,at this point,we will apply Dependency Injection.
We ve created an interface which name was "IConveyance" for DI usage,now we create "Bus","Car","Truck" ...classes.
class Car:IConveyance
{
public void Start()
{
}
public void Stop()
{
}
public void TurnRight()
{
}
public void TurnLeft()
{
}
}
class Bus:IConveyance
{
public void Start()
{
}
public void Stop()
{
}
public void TurnRight()
{
}
public void TurnLeft()
{
}
}
class MotorBike:IConveyance
{
public void Start()
{
}
public void Stop()
{
}
public void TurnRight()
{
}
public void TurnLeft()
{
}
}
Now we are implementing DI to Vehicle class.
class Vehicle
{
IConveyance _conveyance;
public Vehicle(IConveyance conveyance)//DI
{
_conveyance= conveyance;
}
public void UseCar()
{
_conveyance.Start();
_conveyance.TurnRight();
_conveyance.Stop();
_conveyance.TurnLeft();
}
}
Now u can create "Buss" or "MotorBike" classes.And vehicle doesn't interest what you create as an object and it is not contained any parent class.
class Programme
{
static void Main(string)
{
Vehicle vehicleCar= new Vehicle(new Car());
vehicleCar.UseCar();
//or
Vehicle vehicleBus= new Vehicle(new Bus());
vehicleBus.UseCar();
//veya
Vehicle vehicleMotorBike= new Vehicle(new MotorBike());
vehicleMotorBike.UseCar();
}
}
This is Constructor Based Dependency Injection but if you want to Setter Based Dependency Injection changing in the Vehicle class is enough.
Setter Based Dependency Injection
class Vehicle
{
public IConveyance _conveyance{ get;set; }
public void UseCar()
{
_conveyance.Start();
_conveyance.TurnRight();
_conveyance.Stop();
_conveyance.TurnLeft();
}
}