views:

135

answers:

2

I've been following Daniel Cazzulino's series about building a DI container using TDD. In part five of the series, he adds support for container hierarchies without commenting on what makes this feature useful. I've seen mention of support for hierarchies in many of the DI frameworks, but I'm having trouble understanding when they'd be used, and why. Can someone offer some insight?

+1  A: 

I left a comment on kzu's blog asking the same question. It's a shame he didn't clarify the use-case for such a feature before coding it.

The only thing I could think of is if you wanted to have different types resolved from your container in different parts of your app. For example, if you had an order-entry system with two separate sections, and each section was identical except that they needed to present a different product list, you could create a child container for each section, and "override" the registration of your product repository in each. Whenever a section tried to resolve a product repository (or anything that depended on one) it would get the instance you set up in the child container rather than the parent. Sort of like overriding a virtual method.

This might be way off base, but it's the best I could come up with.

Matt Hamilton
A: 

Here's a sample that uses child containers in a scenario similar to the one Matt describes. It uses child containers to select between different database configurations.

The key here is that most of the configuration is shared between the child containers (that shared part belongs in the parent container)

Mauricio Scheffer