Should Unity be configured in code or configuration file?

RB. picture RB. · Mar 24, 2011 · Viewed 7.5k times · Source

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?

Answer

Mark Seemann picture Mark Seemann · Mar 24, 2011

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.

  • Configuration tends to break when you rename types or assemblies.
  • You have to manually copy the appropriate .dlls to the output directory (or have a build script do it).
  • The overall verbosity makes it difficult to work with.
  • Tool support is weaker than for strongly typed code.

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.