是否将DI容器注入(几乎)每个课堂? [英] Is is an anti-pattern to inject DI container to (almost) each class?

查看:103
本文介绍了是否将DI容器注入(几乎)每个课堂?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现自己没有关心一个类的定义依赖关系,并将它们传递给构造函数,但是我只是总是传递DI容器并将其保存在一个私有属性中。这样我的类不会有非常明确的依赖关系,当我需要它时,我从容器中获得所有东西。



不知怎的,我对这个解决方案有不好的感受(除了通过访问容器引起的开销),但是我真的不能想到太多的缺点。也许具有松散的依赖关系可以降低一个类的可移植性,或者在重构时会产生惊喜??



你觉得这个是什么?

解决方案

绝对错了。不要将DI容器放在物体中;他们不需要知道或关心他们被注射。这不符合不要打电话给我们;我们会打电话给你。



这是另一回事:整个应用程序知道DI引擎,但是它从它获取需要的bean。



我想你可能会认为注释会改变一些关系,因为现在bean >知道一些事实,他们被连线在一起。但是,当配置被外部化为XML时,豆是无知的DI。


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.

这篇关于是否将DI容器注入(几乎)每个课堂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆