Chapter 7. Declare Your Independence with Dependency Injection

It is always a good idea to reduce dependencies in your code and abstract as much as possible; but that is not always realistic. It is inevitable that you will introduce dependencies between your classes and even assemblies. Fortunately, there is a way to mitigate the effects of dependencies and reduce the coupling in the code.

Using the Inversion of Control (IoC) and Dependency Injection (DI) principles, we are able to create loosely coupled systems and mitigate the effects of dependencies. Inversion of Control is the indirection of object instantiation so that objects do not directly create other objects. Instead, an IoC Container will inject the dependencies into an object through constructor parameters or public properties.

Combined with mocking, Dependency Injection can greatly simplify testing. Imagine if we have a class that calls a web service. Using DI, we can inject a mocked version of that class which is used for our testing.

Get ASP.NET MVC 1.0 Test Driven Development: Problem - Design - Solution now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.