依赖注入最佳实践和反模式
我在依赖注入方面相对不熟练,我想学习一些在使用 DI 时分别使用和避免的最佳实践和反模式。
I'm relatively unskilled in Dependency Injection, and I'd like to learn some best practices and anti-patterns to use and avoid respectively when using DI.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我真的很喜欢这篇关于 DI 的文章,因为它针对的是那些没有大量 DI 经验,或者甚至不知道它是什么的人。
https://mtaulty.com/2009/08/10/m_11554/
I really enjoyed this article regarding DI, as it's targeted towards people who don't have a ton of DI experience, or don't even know what it is.
https://mtaulty.com/2009/08/10/m_11554/
在我看来,Dhanji Prasanna 的书 依赖注入 是软件设计人员必读的一本书,无论是初学者还是专家。它直接处理您的 DI 问题。
In my opinion, Dhanji Prasanna's book Dependency Injection is a must read for software designers, both beginners and experts. It deals directly with your DI questions.
Guice 的用户指南中有一个最佳实践部分。
There's a best practices section in Guice's user's guide.
我发现,当我看到违反 德米特法则 的行为时,这是一个暗示我可能想要依赖注入。
例如:
有时会提示我可能想要依赖注入
anotherobject
。I've found that when I see a violation of the Law of Demeter that is a hint that I might want dependency injection.
For example:
Sometimes hints that I might want to dependency inject
anotherobject
.我关于何时使用 DI 的基本规则是我将在层之间注入,因此我的控制器和 dao 之间将是一个层,因此我可以注入,这样如果我想模拟一个层我就可以。
我认为在同一层中使用 DI 不是一个好主意,主要是因为层应该紧密耦合,因为它们是相关的,除非您有一个使其有用的用户故事。
例如,如果您的 DAO 可能位于不同的计算机上,那么您可能需要能够假装它们是一层,但使用 DI 在一台计算机上和不同的计算机上实际切换。然后开发人员可以在一台机器上完成所有工作,并且它应该在不同的机器上工作。
但是,除非有迫切的需要,否则我认为同一层内的 DI 是不必要的复杂化。
My basic rule about when to use DI is that I will inject between layers, so between my controller and the dao would be a layer, so I can inject, so that if I want to mock out a layer I can.
I think using DI within the same layer is not a good idea mainly because the layer should be tightly coupled, as they are related, unless you have a user story that makes it useful.
For example, if your DAO is may be on separate computers then you may need to be able to pretend that they are one layer, but use DI to actually switch between all on one machine and separate machines. Then the developer can do everything on one machine and it should work on separate machines.
But, unless there is some pressing need, I think DI within the same layer is an unnecessary complication.
这是依赖注入反模式: 多个构造函数。
Here's a dependency injection anti-pattern: Multiple Constructors.