Microsoft's Unity dependency injection framework can be configured either through code or through the applications configuration file (app.config).
Code example:
IUnityContainer container = new UnityContainer()
.RegisterType<IInterface, ConcreteImplementation>();
Configuration example:
<unity>
<containers>
<container>
<types>
<type type="IInterface, MyAssembly"
mapTo="ConcreteImplementation, MyAssembly" />
What are the advantages/disadvantages to each approach? I can think of the obvious advantage "Users can easily configure your application", and the obvious disadvantage "Users can easily break your application", but is there anything less obvious?
XML configuration is really only beneficial for a single thing: Late Binding. With XML configuration you can change how your application is composed without recompiling the entire application. This is particularly relevant for ISV applications that support a degree of user configuration. ISVs can ship a compiled application with default behavior, but enable customers/users to change parts of the behavior by changing the configuration.
However, XML configuration is brittle and verbose. From a developer's viewpoint, it's just a pain to work with.
As a rule of thumb, prefer Code as Configuration. However, you can match Code as Configuration with XML configuration, so if you have a few dependencies which should be late bound, you can use XML configuration for those.
One significant disadvantage of configuration via code is the code requires a reference to the assemblies. This means I have to add project or DLL references in the project in order for the code to compile.
Dependency injection is supposed to remove dependencies between components. Initialization via code reintroduces the dependency by requiring project or DLL references. The xml configuration file can reference any assembly.
If I create a new implementation based on an interface I can integrate the new implementation into an existing application by adding the compiled DLL and updating the xml configuration file. If I do the configuration via code, I have to recompile the application in order to replace an implementation.
Question is already answered but I want to summarize my experience:
Use both. I'm hiding Code Configuration into Extension, when I have several standard configurations (usually - that because I use IoC) then I have several extensions, that share main configuration.
I'm using XML configuration for non standard tasks like performance tuning (in the environment where the recompilation take a long time).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With