IoC / Dependency Injection - please explain code v

2019-01-07 00:31发布

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?

4条回答
劳资没心,怎么记你
2楼-- · 2019-01-07 00:52

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.

查看更多
叛逆
3楼-- · 2019-01-07 01:02

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.

查看更多
相关推荐>>
4楼-- · 2019-01-07 01:03

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).

查看更多
爷的心禁止访问
5楼-- · 2019-01-07 01:13

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.)

查看更多
登录 后发表回答