I’m trying to hack my own dependency injection container in PHP, based on constructor injection. The container instantiates complex objects and inject them with the required objects based on the type hints in the constructor using reflection.
One thing I obviously stumbled upon is the fact that I can register multiple components that can be injected, of the same type (extending same class / implementing same interface(s)). For example, what if two objects both need distinct objects that both implement an Iterator interface. How do DI Containers typically deal with this? How do you let the container decide which of the objects with the ambiguous interfaces need to be injected in which of the complex objects?
Or is a single DI container only ment to be responsible for creating one type of complex object? In other words: for each complex object instantiate a distinct DI container. I can hardly imagine this is the intent, right?
What you’re describing isn’t DI, per se, but rather autowiring, a step further than plain DI. Normally with DI you explicitly configure which components get wired into what.
Autowired DI is only really desirable with coarse-grained components, where there’s only one sensible implementation of the given type (e.g. DAOs). In cases where the type is ambiguous, then you either mark one of them as the “primary”, or mark the others as “not candidates”, or explicitly mark the dependency with the name of the component you need.
If it helps, you could read up on how Spring handles autowiring here and here