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

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

问题描述

我理解基本上IoC框架如何工作,但是我不太明白的是基于代码的配置是如何工作的。使用XML,我了解如何向已部署的应用程序添加新的程序集,然后将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屋!

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