Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Dependency Injection frameworks support container hierarchies?

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?

like image 633
Josh Avatar asked Feb 03 '09 00:02

Josh


People also ask

What is container in dependency injection?

A DI Container is a framework to create dependencies and inject them automatically when required. It automatically creates objects based on the request and injects them when required. DI Container helps us to manage dependencies within the application in a simple and easy way.

Why do we need dependency injection framework?

The Dependency Injection Framework is used when somebody calls the constructor. The Framework will Inject the concrete implementation of the ICompaniesService rather than the developer explicitly calling the constructor. While it is a specific product, the nInject Homepage actually has some really good examples.


1 Answers

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.

like image 71
Matt Hamilton Avatar answered Oct 22 '22 19:10

Matt Hamilton