What is Dependency Injection (DI), and why should you care?

Posted: (EET/GMT+2)

 

For a long time, unit testing software applications was something that only those interested in latest trends or academia did. Today, unit testing can be said of as being a mainstream technology, and even the smallest ISVs are focusing on it. For .NET developers, both Visual Studio 2008 and 2010 have great support for unit testing right out of the box, if you are using the Professional editions or above.

In simple terms, unit tests can be thought of as a safeguard against future code changes. Often as projects become larger, the fear of change can affect future enhancement possibilities, because developers are afraid to break something that already worked. Unit tests can lessen this fear.

Now, unit tests cannot be something that you glue in later once you are done with your coding. Instead, you should plan for testability while writing your code. On the other extreme, the TDD (test-driven development) writes unit tests even before the actual code. In any case, you will need to write code and use architectures that help in achieving your goal.

One of the coding-side enablers in testability is Dependency Injection or DI. You might have heard the term, and maybe even have used it even if you are not aware of the term. The basic idea of Dependency Injection is that you should write code that is loosely-coupled, and objects should not expect specific object types to communicate with each other. Instead, you should interfaces for more generic usability.

This generic model is very important so that you can use mock objects to help in the testing in place of real object types that can be difficult to automate and/or test in tandem. Wikipedia for instance has an article about Dependency Injection, and so does MSDN Documentation.

In addition to the concept of Dependency Injection, there are many ready-made frameworks for C# and .NET developers that can be used. Three of the popular ones include Unity, Spring.NET and to certain extent Managed Extensibility Framework or MEF.

If you are interested in code testability, but are not yet familiar with the concept of DI, now it's a good time to start learning. Lots of material is already available, so take use of it!