gpt4 book ai didi

c# - 依赖注入(inject)容器?它有什么作用?

转载 作者:可可西里 更新时间:2023-11-01 08:08:01 26 4
gpt4 key购买 nike

我一直在阅读有关 DI 的资料,它似乎是一个足够简单的概念。我没有得到的是容器。假设我想创建自己的容器。使用了像“检测”这样的动词,但我不明白容器是如何“检测”到一个新的依赖对象已创建并知道注入(inject)它的依赖项的。在我看来,容器就像是一家美化的工厂。

任何人都可以解释容器的实际实现方式,或者可以为我指出一种资源吗?

谢谢!

最佳答案

这取自Windsor documentation

Inversion of Control

Inversion of Control is a principle used by frameworks as a way to allow developers to extend the framework or create applications using it. The basic idea is that the framework is aware of the programmer's objects and makes invocations on them.

This is the opposite of using an API, where the developer's code makes the invocations to the API code. Hence, frameworks invert the control: it is not the developer code that is in charge, instead the framework makes the calls based on some stimulus.

You have probably been in situations where you have developed under the light of this principle, even though you were not aware of it.

Inversion of Control Container

An Inversion of Control Container uses the principle stated above to (in a nutshell) manage classes. That is, their creation, destruction, lifetime, configuration, and dependencies. This way classes do not need to obtain and configure the classes they depend on. This dramatically reduces coupling in a system and, as a consequence, simplifies reuse and testability.

There is some confusion created by people that think that 'Inversion of Control' is a synonym for 'Inversion of Control Container'. As stated, Inversion of control is a broader principle.

Often people think that it is all about "injection", and broadcast that this is the primary purpose of IoC containers. In fact, "injection" is a consequence, a means to decouple, not the primary purpose.

关于c# - 依赖注入(inject)容器?它有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8015101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com