Friday, April 17, 2015

Understand Dependency Injection with C# code example

Dependency Injection (DI) is a design pattern that demonstrates how to create loosely coupled classes. It can be implemented by constructor injection, setter injection or method injection.
To understand DI you need to understand how and why DI pattern introduced. Following terms are the main factor for complete understanding of DI.  
  • Dependency
  • Dependency Inversion Principle
  • Inversion of Control (IoC)
Below diagram will depicts the differences between these terms, it's pros and cons and complete journey. code will help to understand this patterns easily.

Main advantages of using DI patterns
  • Create loosely couple class, reduces class coupling
  • Improves application testing, Classes can be tested individually, Class can be mock easily.,  
  • Increases code re-usability
  • Improves code maintainability
  • Increase application scalability
Dependency injection can be done in three ways.
  • Constructor injection
  • Method injection
  • Property injection
In below diagram I have described the Constructor injection, other example can be seen in below links
Microsoft provide better framework called unity 3.0 (latest )to develop DI pattern, this can be downloaded by below link
Dependency Injection using unity framework, C# code example can be seen in below link
There are reasons for not using it in your application, some of which are summarized in this section.

  • Dependency injection can be overkill an application, introducing additional complexity and requirements that are not appropriate or useful. this has to be used properly after good analysis of all aspects.

No comments: