Advanced Configuration Engine for Unity

The out-of-the-box configuration engine of Unity is one of the areas where Unity cannot compete with the convenience that other containers offer. While most of these have their own DSLs for configuration and support various conventions, Unity only has its RegisterType() and RegisterInstance() Methods. This makes for rather verbose configuration of the container.

Forgery Imitation is the biggest compliment you can get. Having said this: TecX.Unity\Configuration is my compliment to Jeremy Miller's StructureMap. StructureMap and Unity are too different in their internal architecture to be able to just copy what StructureMap does. But with some tweaking it is possible to adapt its mechanics and bring all the richness of encapsulated configurations, automatisms and conventions to Unity as well.

Have a look at the following code snippet:
ConfigurationBuilder builder = new ConfigurationBuilder();

builder.Scan(
  scanner =>
    {
      scanner.LookForConfigBuilders();
      scanner.AssembliesFromApplicationBaseDirectory();
    });

container.AddExtension(builder);

It searches all assemblies in the current application base directory for classes that inherit from ConfigurationBuilder. Each of these classes encapsulates a specific aspect of the configuration of Unity. You can structure your application in modules and each module can have its own config.

The following example configures parts of a Caliburn.Micro-based application via a class derived from ConfigurationBuilder.

public class CaliburnConfigurationBuilder : ConfigurationBuilder
{
  public CaliburnConfigurationBuilder()
  {
    For<ShellViewModel>().Use<ShellViewModel>().AsSingleton();
    For<IShell>().Use<ShellViewModel>().AsSingleton();
    For<IWindowManager>().Use<WindowManager>().AsSingleton();
  }
}

Or you can use conventions to automate your registrations. The following snippet registers all classes that are named like an interface but without the I-prefix (e.g. class Foo will be registered as implementation for interface IFoo).

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.Scan(
  scanner =>
    {
      scanner.TheCallingAssembly();
      scanner.With(new ImplementsIInterfaceNameConvention());
    });

The source code can be found in the TecX.Unity project (folder Configuration). Tests that document how to use it are placed in TecX.Unity.Configuration.Test.

Last edited Jun 11, 2012 at 8:23 AM by weberse, version 4

Comments

No comments yet.