Thursday, December 01, 2011

When not to use Dependency Injection?

Dependency Inject and Inversion of Control are too popular for people to think when not to use them.

DI / IoC encourages high-level modules define abstract services for low-level modules to implement. The changes of the implementation in low-level modules won't affect the defined interfaces, so high-level modules can remain stable. Unit tests to high-level modules can be conducted even when mocked low-level modules are provided.

From this understanding, it’s always a good idea to use DI / IoC between layers in a multi-tier software architecture. On the contrary, whether or not to use DI / IoC within the same tier should be carefully examined. In most cases, factory method or even new statement will do. Here are a couple of reasons.

1. The components within same tier are usually tightly coupled. Changing one component and related components need to change accordingly is sometimes reasonable, if compared to inter-tier cases.

2. Within same tier, large amount of business objects may be created. This is very different from injecting a low-level service provider to high-level module. The performance of reflection in creating large amount of objects in IoC container may hurt the system.

No comments:

Post a Comment