According to
the above picture Interface is very important thing in DI. All the methods that
we can access through interface layer.
There are
three types of Dependency Injection
- · Constructor Injection
- · Property Injection
- · Method Injection
Let’s go
through above three types with sample codes
Constructor
Injection
This is the
most commonly used Dependency Pattern.
This pattern
is done by supplying the dependency through the class’s constructor when
instantiating that class.
public interface IDataLayer
{
void DoDataLayerLogic();
}
public class DataLayer : IDataLayer
{
public void DoDataLayerLogic()
{
Console.WriteLine("Data Layer Logic Done");
}
}
public class BussinessLogicLayer
{
private IDataLayer _dataLayer;
public BussinessLogicLayer(IDataLayer dataLayer)
{
this._dataLayer = dataLayer;
}
public void DoBussinessLogic()
{
Console.WriteLine("Service Started");
this._dataLayer.DoDataLayerLogic();
}
}
{
void DoDataLayerLogic();
}
public class DataLayer : IDataLayer
{
public void DoDataLayerLogic()
{
Console.WriteLine("Data Layer Logic Done");
}
}
public class BussinessLogicLayer
{
private IDataLayer _dataLayer;
public BussinessLogicLayer(IDataLayer dataLayer)
{
this._dataLayer = dataLayer;
}
public void DoBussinessLogic()
{
Console.WriteLine("Service Started");
this._dataLayer.DoDataLayerLogic();
}
}
