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 Inversion Principle
- Inversion of Control (IoC)
Below diagram will depicts the differences between these terms, it's pros and cons and complete journey. C#.net code will help to understand this patterns easily.
Dependency Injection using unity framework, C# code example can be seen in below link
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
- Constructor injection
- Method injection
- Property injection
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.