开发者

IoC / Dependency Injection - please explain code versus 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 开发者_如何学CXML 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 and Dep injection can help allow changes without recompiling (depending on the tools used), but don't require it. Using code to configure is about configuring the container, not about post-deployment changes. Yes, if you make the change in code you normally need to recompile.


Change of code without recompilation, Is NOT possible. Change of configuration stored in Web.Config, without reloading the App Pool is NOT possible. However, you may employ the following scenario where you don't have to recompile the code or recycle the App Pool.
1. Store your Mappings in an external config file. (XML is fine)
2. Write a function which loads the mappings from the external file to your container.
3. Expose a function which reloads the mappings.
4. Whenever you want to reload the mappings, simply call the exposed method and you are good to go :)

You may also store the mappings, in a SQL server, or any other place. (Simply load them into the required format for the container to process it.)


Just because a DI container uses code for configuration doesn't mean that no configuration can be changed without recompiling. It does require that you think about exactly what you want to be configurable that way and provide some means of changing that configuration (such as through a properties file).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜