Friday, September 9, 2011

Dependency Injection (DI) – How and Why

There are two ways to implement dependency injection (DI) – through the class's constructor or its property setter. In class's constructor or the setter, instead of passing in a concrete class type parameter, use an interface. This way, you can later pass in different class objects that implement this same interface. The decoupling between the class constructor / setter and a concrete type provides the needed flexibility and scalability.

With this design, your classes are more unit-testable. You can create a mock class to implement the same interface as the real one, and pass in the mock object to the constructor or the setter. In the mock class, instead of connecting to a physical database server, you can set sample values as you wish. However, this would not eliminate the necessities to do your integration testing by connecting to the real database later.

Overall, the usage of DI will make your class handle less and less dependencies with concrete types, thus make it much more scalable.

No comments:

Post a Comment