Friday, February 24, 2012

Dependency Injection : A pattern for loose coupling

What is Dependency Injection?

Dependency Injection means dynamically inserting code at run time. So that application behavior can be change without affecting/recompiling whole application.

How this Injection is helpful?

Most of the application have many component which are depending on other i.e.  One component needs other to complete their job, know as Dependencies.
The purpose of most of the application architecture is to reduce the coupling between component to make the application more configurable & more loosely coupled. So that changes in one component doesn't affect other component.

Lets look at an example:-
public class BankAccount {
  private ILogger _logger = new DBLogger();

  public void Deposit(decimal amount) {
    // logic to update account
    _logger.LogTransaction(
       string.Format("Amount deposited at {0}", DateTime.Now));
  }

  public void Withdraw(decimal amount) {
    // logic to update account
    _logger.LogTransaction(
       string.Format("Amount withdraw at {0}", DateTime.Now));
  }

}
 
DBLogger object is directly instantiated inside the BankAccount class so BankAccount should know in advance about the DBLogger implementation and to change another implementation of ILogger we need to change BankAccount class too.
Lets we have another implementation of ILogger for text file logging.

public class DBLogger : ILogger {

  #region ILogger Members

    public void LogTransaction(string message) {
     // Logic to log the message to database.
    }

  #endregion
}

public class TextFileLogger : ILogger {

  #region ILogger Members

    public void LogTransaction(string message) {
      // Logic to log the message to text file.
    }

  #endregion

}
 
public interface ILogger {
  void LogTransaction(string message);
}
 
To change DBLogger to TextFileLogger in BankAccount, we need to compile BankAccount class too.

Dependency Injection (DI) remove these kind of tight coupling between component by injecting the dependency at run time.So dependent class doesn't know about the dependency at design time, DI injects dependency object's instance at run time. Based on the configuration, DI will inject the ILogger implementation in BankAccount class.

Dependency injection can be possible by three ways:
  1. Interface Injection
  2. Setter Injection
  3. Constructor Injection
Microsoft Enterprise Library provides the DI framework for all .Net applications.I am referencing MS Enterprise Library 5.0 that can be download from here .In EntLib 5.0, Policy Injection Block is kept just for the compatibility with previous version. Dependency configuration using EntLib 5.0 can be possible either by Code or by .Net configuration file.

I will continue about the dependency injection type in my next articles.

No comments:

Post a Comment