有人说使用依赖注入更好。 这是为什么?
我认为最好是有几个全球性的,容易接近的课程,而不是庞大的构造函数。
它以任何方式影响应用程序速度?
这两个组合可能是最好的。
Some people say that it is better to use dependency injection. Why is that?
I think it is better to have few global, easy accessible classes, rather than huge constructors.
Does it influence application speed in any way?
Mix of these two would be probably the best.
最满意答案
主要优点是解耦 ,这将有助于单元测试。 这完全取决于你如何编写这些“易于访问的类”。
这个想法是这样的。 一个类通过只依赖合约 ( interface )而从实现 ( class )依赖关系中解耦。 在你的实际环境中,你可能永远不会提供一个新的实现类,但是在你的测试环境中,你很可能会(不论是手工制作的存根,还是来自模拟框架的模拟类)。
应用程序速度需要分析,但是使用DI框架可能会产生一些开销,而不是直接与您了解的单例进行对话。 重要的问题是:这种开销是一个问题吗? 只有性能预期和性能分析才能告诉你。 根据我的经验,这些好处远远超过可忽略的性能损害。
The main advantage will be decoupling, which will help with unit testing. This sort of depends entirely on how you code these "easily accessible classes".
The idea is this. A class decouples from implementation (class) dependencies by only having a dependency on the contract (interface). In your live environment you may never provide a new implementing class, but in your test environment you very likely will (be it a handmade stub, or a mocked class from a mocking framework).
Application speed would need profiling, but the use of a framework for DI would likely incur some overhead instead of you talking directly to a singleton that you know about. The important question: is this overhead a problem? Only performance expectations and profiling can tell you that. In my experience, the benefits far outweigh the negligible performance detriment.
更多推荐
发布评论