IoC/依赖注入 - 请解释代码与 XML [英] IoC / Dependency Injection - please explain code versus XML

查看:19
本文介绍了IoC/依赖注入 - 请解释代码与 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上了解 IoC 框架的工作原理,但是我不太明白的一件事是基于代码的配置应该如何工作.使用 XML,我了解如何向已部署的应用程序添加新程序集,然后更改 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?

推荐答案

热插拔依赖项并不是使用 DI 容器的唯一目标.

Hot-swapping dependencies is not the only goal of using a DI Container.

依赖注入 (DI) 是一种帮助我们开发松散耦合代码的原则.松散耦合仅意味着我们可以彼此独立地改变消费者和服务.我们如何实现这一点在此级别未解决.

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 是有助于一起使用连线依赖项的框架.它们或多或少只是帮助我们应用 DI 模式的实用程序库.再一次,如何配置容器与我们如何使用这些依赖项是垂直的.

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 配置允许我们无需重新编译即可更改容器配置.代码作为配置没有.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆