Xml configuration or Configuration through code?

后端 未结 2 385
醉梦人生
醉梦人生 2020-12-10 14:29

I personally like the option to configure StructureMap from C# code. From what I understand, one of the advantages of DI, is that we can easily swap in a new concrete instan

2条回答
  •  青春惊慌失措
    2020-12-10 14:49

    No matter which particular DI Container you use, you should always defer the resolution of the application's object graph to the last responsible moment. This is called the application's Composition Root.

    You can write the bulk of your application without ever referencing the DI Container. This also means that you can defer the decision between configuration in code or config until you need it.

    You shouldn't need the container at all for unit testing, but may need it for integration testing. However, in integration tests, you will likely need a different configuration for the container than in the final application.

    All in all, configuring the container in code is the preferred approach these days because it's more robust and you can apply convention-based configuration mechanics.

    XML configuration tends to be more brittle and too verbose. In most cases, it simply slows you down because you get no refactoring or compiler support.

    However, XML configuration is still valid when you need to be able to swap dependencies without recompiling the application. Most DI Containers will let you mix those approaches so that you can have most of your configuration in code, but a few selected dependencies defined in XML for extensibility reasons.

提交回复
热议问题