Lately I find myself not caring too much defining dependencies for a class and passing them in the constructor, but I just always pass the DI container and keep it in a private attribute. This way my class won’t have very well-defined dependencies, I get everything from the container when I need it.
Somehow I have bad feelings about this solution though (apart from the overhead caused by accessing the container), but I can’t really think of too much disadvantages. Maybe having loose definition of dependencies can decrease portability of a class, or I get surprises when refactoring…?
What do you think about this?
Absolutely wrong. Don’t put the DI container in the objects; they need not know or care that they’re being injected. This doesn’t square with “don’t call us; we’ll call you.”
It’s the other way ’round: the overall app knows about the DI engine, but then it gets the beans it needs from it.
I suppose you might argue that annotations change the relationship some, because now the beans do know something about the fact that they’re wired together. But when configuration was externalized into XML, it was true that beans were ignorant of DI.