IoC /依赖注入 - 请解释代码与XML [英] IoC / Dependency Injection - please explain code versus XML
问题描述
热插拔依赖关系不是唯一的目标使用DI容器。
依赖注入(DI)是帮助我们开发松散耦合代码的原则。松耦合只意味着我们可以独立于彼此改变消费者和服务。 我们实现这一点在这个层次上没有得到解决。
DI容器是有助于一起使用电线依赖关系的框架。他们或多或少仅仅是帮助我们应用DI模式的实用程序库。再次,我们配置容器的方式与我们如何使用这些依赖关系是一样的。
XML配置允许我们更改容器配置而不重新编译。代码作为配置不会。
但是,不重新编译的交换依赖关系通常只适用于所有松散耦合代码的小子集。对于其余的,基于惯例的方法更有效,因为它往往不那么脆弱。有关详细信息,请参见此处。
I understand basically how IoC frameworks work, however one thing I don't quite get is how code-based config is supposed to work. With XML I understand how you could add a new assembly to a deployed application, then change the config in XML to include it. If the application is already deployed (i.e., compiled in some form) then how can code changes be made without recompiling? Or is that what people do, just change config in code and recompile?
Hot-swapping dependencies is not the only goal of using a DI Container.
Dependency Injection (DI) is a principle that helps us develop loosely coupled code. Loose coupling only means that we can vary consumer and service independently of each other. How we achieve this is not addressed at this level.
DI Containers are frameworks that help use wire dependencies together. They are more or less just utility libraries that help us apply DI patterns. Once again, how we configure a container is perpendicular to how we consume those dependencies.
XML configurations allows us to change the container configuration without recompilation. Code as configuration doesn't.
However, swapping dependencies without recompilation is typically only relevant for a small subset of all your loosely coupled code. For the rest, a convention-based approach is much more effective, because it tends to be less brittle. See here for more information.
这篇关于IoC /依赖注入 - 请解释代码与XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!