views:

46

answers:

1

I recently ran across this great article by Chad Parry entitled "DIY-DI" or "Do-It-Yourself Dependency Injection". I'm in a position where I'm not yet ready to use a IoC framework, but I want to head in that direction. It seems like DIY-DI is a good first step.

However, after reading the article, I'm still a little confused about object creation. Here's a simple example:

http://yfrog.com/jxhotelip

alt textalt text

Using manual constructor dependency injection (not DIY-DI), this is how one must construct a Hotel object:

PowerGrid powerGrid;           // only one in the entire application
WaterSupply waterSupply;   // only one in the entire application

Staff staff;
Rooms rooms;
Hotel hotel(staff, rooms, powerGrid, waterSupply);

Creating all of these dependency objects makes it difficult to construct the Hotel object in isolation, which means that writing unit tests for Hotel will be difficult.

Does using DIY-DI make it easier?
What advantage does DIY-DI provide over manual constructor dependency injection?

+1  A: 

There's no difference between what you call DIY-DI and manual constructor injection.

If it's too difficult creating a Hotel instance you can do two things:

  • Make sure that the dependencies are expressed as either interfaces or abstract base classes. This lets you test the Hotel class in isolation by providing Test Doubles such as dynamic mocks or similar instead of concrete classes.
  • If there are too many dependencies, then refactor to aggregate services.

As an application grows in complexity, so does the task of managing the lifetimes of all dependencies. While it's technically possible to manually compose an entire application, this is exactly the point where a DI Container can be extremely helpful.

Mark Seemann