依赖注入作为一种语言特性?
是否有任何现有的现代编程语言明确将依赖项注入作为语言功能,如果是,是否有任何示例说明此类编程语言如何使用其语法将程序依赖项与其具体实现分开?
(请注意:我并不是在寻找 DI/IOC 框架——我实际上是在寻找一种实际上内置了此功能的编程语言)。
Are there any existing modern-day programming languages that explicitly have dependency injection as a language feature, and if so, are there any examples of how such programming languages use their syntax to separate program dependencies from their concrete implementations?
(Please Note: I'm not looking for an DI/IOC framework--I'm actually looking for a programming language that actually has this feature built into the language).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不会发现依赖注入是一种语言功能,因为它通常被视为一种设计模式。设计模式是作为缺少语言功能的解决方法而出现的 - 例如,如果您将第一类类型作为语言功能,则不需要工厂模式(请参阅 Norvig 的演示 ),如果您有多种方法作为语言功能,则不需要双重调度模式。
以 DI 为设计模式的语言特性是“参数化模块”。请参阅模块的讨论与 DI 相关吉拉德·布拉查 (Gilad Bracha) 的语言 Newspeak
You won't find dependency injection as a language feature, as it's generally seen as a design pattern. Design patterns arise as workarounds for missing language features - for example if you have first class types as a language feature you don't need the factory pattern ( see p12 of Norvig's presentation ), if you have multi-methods as a language feature you don't need the double dispatch pattern.
The language feature for which DI is the design pattern is "parametric modules". See the discussion of modules vs DI relating to Gilad Bracha's language Newspeak
我不想听起来像个混蛋,但每种面向对象语言都支持依赖注入。不需要特殊的语法。只需使用它们的依赖项构造您的对象(或稍后设置它们的依赖项)。
实际上,您可以将所有依赖项连接到程序顶部附近的某个位置 - 不一定是
main()
,但靠近顶部。I don't mean to sound like a jerk, but every OO language supports dependency injection. No special syntax is required. Just construct your object with their dependencies (or set their dependencies later).
You can actually wire up all your dependencies somewhere near the top of the program - not necessarily
main()
, but close to the top.Noop 据说可以做到这一点,但我还没有看到语言规范(我的耐心耗尽了在我找到它之前)。
Noop supposedly does this, but I haven't seen the language specification (my patience ran out before I found it).
可以说,Scala 在特征和自类型注释的帮助下支持开箱即用的依赖注入。看一下蛋糕模式:
http:// jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/
基本上,这种方法使用具有声明的依赖项的特征(通过使用自类型)来让编译器完成以下工作将它们连接在一起。
这是声明注册表:
...注册用户存储库:
...以及依赖于存储库的用户服务组件:
One could say that Scala supports dependency injection out of the box with the help of traits and self-type annotations. Take a look on a Cake Pattern:
http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/
Basically, this approach uses traits with declared dependencies (by using self-types) to let the compiler do the work of wiring them together.
This is the declaration registry:
...registering the user repository:
...and the user service component that depends on the repository: