Thursday, June 2, 2016

Dependency Injection

  • If no Dependency Injection, customer point to DatabaseHelper now, future have XMLDatabase, you would change lot of code.
  • Dependency Injection is good; it makes the classes loose couple.
  • It achieves Dependency Inversion Principle. (High-level modules should not depend on low-level modules. Both should depend on abstractions.) [Customer is High Level, DatabaseHelper is low level, IStorage is High Level]
  • Is to pass the variable into Constructor, Default Constructor is to initialize the concrete class.
static void Main(string[] args)
{
       var customera = new Customer(new DatabaseHelper());
       customera.CustStore();

       var customerb = new Customer(new XMLHelper());
       customerb.CustStore();

       Console.ReadLine();
}

public class Customer
{
    private IStorageHelper _iStorageHelper;

    public Customer(IStorageHelper iStorageHelper)
    {
        _iStorageHelper = iStorageHelper;
    }

    public void CustStore()
    {
        _iStorageHelper.Store();
    }
}

public interface IStorageHelper
{
    void Store();
}

public class DatabaseHelper : IStorageHelper
{
    public void Store()
    {
        Console.WriteLine("DB Store");
    }
}

public class XMLHelper : IStorageHelper
{
    public void Store()
    {
        Console.WriteLine("XML Store");
    }
}

No comments:

Post a Comment