IoC.Resolve VS构造器注入 [英] IoC.Resolve vs Constructor Injection

查看:358
本文介绍了IoC.Resolve VS构造器注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听到很多人说,这是一个不好的做法,使用IoC.Resolve(),但我从来没有听说过一个很好的理由(如果它的全部测试,而不是你可以嘲笑的容器,而你完成)。

I heard a lot of people saying that it is a bad practice to use IoC.Resolve(), but I never heard a good reason why (if it's all about testing than you can just mock the container, and you're done).

现在使用的,而不是构造器注入解决的优点是你不需要创建 有5个参数的构造函数和类时,你要创建一个实例 该类你不会需要为它提供什么

now the advantages of using Resolve instead of Constructor Injection is that you don't need to create classes that have 5 parameters in the constructor, and whenever you are going to create a instance of that class you're not gonna need to provide it with anything

推荐答案

IoC.Resolve<> Service地点模式。这种模式规定了一些限制条件构造器注入不会:

IoC.Resolve<> is an example of the Service Locator pattern. That pattern imposes a few restrictions that constructor injection does not:

  • 对象可以没有更精细的环境比应用领域,由于静态调用
  • 对象决定的依赖哪个版本的解决。某一类的所有实例都将获得相同的依赖配置。
  • 的诱惑,夫妇code到容器的高,例如,而不是创建一个意向揭示的工厂。
  • 在单元测试需要容器的配置,其中可能只是被创建和使用的类除外。 (这是当你要测试的同一类的多种配置,由于上面的第二个问题特别麻烦。)
  • 一个应用程序的结构不能从它的公共API推断。 (构造函数的参数是的事情。他们不是一个问题,你应该觉得有必要解决的问题。)
  • Objects can have no more fine-grained context than the application domain, due to the static calls
  • Objects decide which versions of dependencies to resolve. All instances of a certain class will get the same dependency configuration.
  • The temptation to couple code to the container is high, for example instead of creating an intention-revealing factory.
  • Unit testing requires container configuration, where the classes could just be created and used otherwise. (This is especially troublesome when you want to test multiple configurations of the same class, due to the second issue above.)
  • An application's structure cannot be inferred from its public API. (Constructor parameters are a good thing. They are not a problem you should feel the need to solve.)

这些限制,在我心中,贬谪Service Locator模式之间的大球泥和依赖注入一个中间地带:有用的,如果你必须使用它,但远远不是最好的选择。

These limitations, in my mind, relegate the Service Locator pattern to a middle ground between big-ball-of-mud and dependency injection: useful if you must use it, but by far not the best choice.

这篇关于IoC.Resolve VS构造器注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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