Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

dependency injection - Is is an anti-pattern to inject DI container to (almost) each class?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...