I believe that most IoC containers allow you to wire dependencies with XML configuration file. What are cons and pros for using configuration file vs. registering dependencies in code?
I'm assuming that by "registering dependencies in code" you mean "use new".
'new' is an extraordinarily powerful dependency injection framework. It allows you to "inject" your "dependencies" at the time of object creation - meaning no forgotten parameters, or half-constructed objects.
The other major potential benefit is that when you use refactoring tools (say in Resharper, or IntelliJ), the calls to new change too
Otherwise you can use some XML nonsense and refactor with XSL.
XML pros:
- Can change wiring and parameters without recompiling. Sometimes this is nice to have when switching environments (e.g. you can switch a fake email sender used in dev to the real email sender in production)
Code pros:
- Can take advantage of strongly-typed languages (e.g. C#, Java)
- Some compile-time checking (can't statically check dependencies, though)
- Refactorable using regular refactoring tools.
- Can take advantage of DSLs (e.g. Binsor, Fluent interfaces)
- Less verbose than XML (e.g. you don't need to always specify the whole assembly qualified name (when talking .net))
These pros and cons are based on my work with spring. It may be slightly different for other containers.
XML
pro
- flexible
- more powerful than annotations in some areas
- very explicit modelling of the dependencies of your classes
con
- verbose
- difficulties with refactoring
- switching between several files
Annotations
pro
- less file switching
- auto configuration for simple wirings
- less verbose than xml
con
- more deployment specific data in your code (usually you can override this with xml configs)
- xml is almopst(?) always needed, at least to set up the annonation based config
- annotation magic may lead to confusion when searching for the class that is used as dependency
Code
pro
- Can take advantage of strongly-typed languages (e.g. C#, Java)
- Some compile-time checking (can't statically check dependencies, though)
- Can take advantage of DSLs (e.g. Binsor, Fluent interfaces)
- Less verbose than XML (e.g. you don't need to always specify the whole assembly qualified name (when talking .net))
con
- wiring via code may lead to complex wirings
- hard dependencies to IOC container in the codebase
I am using a mix of XML+Annotation. Some things especially regarding database access are always configured via xml, while things like the controllers or services are mostly configured via annotations in the code.
[EDIT: I have borrowed Mauschs code PROs]
I concur. I have found ioc containers to give me very little, however they can very easily make it harder to do something. I can solve most of the problems I face just by using my programming language of choice, which have allways turned out to be simpler easier to maintain and easier to navigate.