傻瓜式控制反转(IoC/依赖注入)

发布于 2024-10-08 17:15:03 字数 407 浏览 0 评论 0原文

可能的重复:
什么是控制反转?

好的,我是这个网站的新手,我'我发现人们真的很愿意提供帮助,所以如果您不介意的话,我会利用这一点并问另一个问题。

所以,我读了很多书,我发誓,但是,我似乎无法弄清楚。控制反转(IoC 或依赖注入)到底是什么?为什么 ASP.NET MVC + Repository Pattern 项目如此频繁地使用它?最后,当他们说“注入我的控制器”时,“容器”是什么意思?

我知道这可能是一个老话题(甚至是一个愚蠢的问题),但我似乎无法得到任何傻瓜答案。

Possible Duplicate:
What is Inversion of Control?

Okay, I'm new to this site and I've seen that people is really willing to help, so imma take advantage of that and just ask another question if you don't mind.

So, I've readed a lot, I swear, BUT, I just can't seem to figure it out. WHAT in the world is Inversion of Control (IoC or Dependency Injection)? Why are ASP.NET MVC + Repository Pattern projects using it so much? And lastly, what they mean by "containers" and when they say "Inject my Controllers"?

I know it might be an old topic (or even a dumb question) but I just can't seem to get any for-dummies answers.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的憧憬 2024-10-15 17:15:04

简单的答案:它让您任何给定对象将用来完成其工作的“东西”。

人为的示例:假设该对象出于某种目的想要获取时间,您向它传递一个“ITimeService”,它会调用“GetTime”。

这样做的目的是使类与您可能不希望发生的事情“脱钩”,并帮助测试。

以我的愚见,有些人有点过头了,但测试论点是有效的,而且当然这是一种有时采用的有用方法。

更多涉及的答案:Martin Fowler 的控制反转

Simple answer: It lets you hand in the "things" that any given object will use to do its work.

Contrived Example: Say the object wants to get the time for some purpose, you hand it a "ITimeService" and it calls "GetTime" on that.

The purpose of this is to "de-couple" the class from having hard relationships to things you may not wish it, and to aid testing.

In my humble opinion some people go a little overboard, but the testing argument is a valid one, and certainly it's an approach that is useful to adopt at times.

More involved answer: Martin Fowler on Inversion of Control.

旧城烟雨 2024-10-15 17:15:03

将依赖注入/控制反转视为一个大对象工厂,一个声明性的、配置驱动的虚拟构造函数。现在,您将让虚拟构造函数为您实例化对象,而不是通过调用“new”来硬连接您的客户端类使用的具体类型来编写代码。

所有这些复杂性给你带来了什么好处?

对象创建现在是一个声明性的事情。如果您碰巧将设计基于适当的接口,则可以要求对象工厂在方便时创建一个实现相同接口的代理。现在,各种美好的事情都成为可能:面向方面的编程、透明的远程处理、声明性事务等。

Think of Dependency Injection/Inversion of Control as little more than a big object factory, a declarative, configuration-driven virtual constructor. Instead of littering your code with calls to "new" that hardwire the concrete type that your client class uses, you're now going to have that virtual constructor instantiate objects for you.

What's the advantage that all that complexity is buying you?

Object creation is now a declarative thing. If you happen to base your design on appropriate interfaces, you can ask the the object factory to create a proxy that implements the same interface when it's convenient. All kinds of good things are now possible: aspect-oriented programming, transparent remoting, declarative transactions, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文