Is testability alone justification for dependency injection?

Posted by fearofawhackplanet on Stack Overflow See other posts from Stack Overflow or by fearofawhackplanet
Published on 2010-06-06T20:17:58Z Indexed on 2010/06/06 20:22 UTC
Read the original article Hit count: 324

The advantages of DI, as far as I am aware, are:

  • Reduced Dependencies
  • More Reusable Code
  • More Testable Code
  • More Readable Code

Say I have a repository, OrderRepository, which acts as a repository for an Order object generated through a Linq to Sql dbml. I can't make my orders repository generic as it performs mapping between the Linq Order entity and my own Order POCO domain class.

Since the OrderRepository by necessity is dependent on a specific Linq to Sql DataContext, parameter passing of the DataContext can't really be said to make the code reuseable or reduce dependencies in any meaningful way.

It also makes the code harder to read, as to instantiate the repository I now need to write

new OrdersRepository(new MyLinqDataContext())

which additionally is contrary to the main purpose of the repository, that being to abstract/hide the existence of the DataContext from consuming code.

So in general I think this would be a pretty horrible design, but it would give the benefit of facilitating unit testing. Is this enough justification? Or is there a third way? I'd be very interested in hearing opinions.

© Stack Overflow or respective owner

Related posts about c#

Related posts about unit-testing