The Builder Pattern

A couple of years ago Jan van Ryjswyck published some articles on the Builder Pattern.

In his series he describes the pattern in the context of test data creation

While it is absolutely true that this pattern is very useful when you have to repeatedly create test data with small variations it does not stop there!

Frameworks like Enterprise Library or AutoFac use the same pattern to create their configuration settings.

IConfigurationSource configSource = new DictionaryConfigurationSource();
ConfigurationSourceBuilder builder = new ConfigurationSourceBuilder();

builder.ConfigureLogging()
  .LogToCategoryNamed("DataAccess")
  .SendTo.RollingFile("MyListener")
    .FormatWith(
      new FormatterBuilder()
        .TextFormatterNamed("MyFormatter")
        .UsingTemplate("{timestamp} {message}"));

builder.UpdateConfigurationWithReplace(configSource);
IUnityContainer container = new UnityContainer();
IContainerConfigurator configurator = new UnityContainerConfigurator(container);
EnterpriseLibraryContainer.ConfigureContainer(configurator, configSource);

But it still doesn’t stop there! If you are developing a component that others will have to use, builders are a way to use Dependency Injection in your code but neither enforce the usage of a specific DI container nor the usage of the DI Pattern at all on these consumers.

Mark Seemann, author of Dependency Injection in .NET, outlines how this can be done in his answer to a question on StackOverflow.

You can encapsulate meaningful default values in your builders whitout poluting your API with various constructor overloads. This allows novice consumers to use your components easily while experts can swap the defaults for custom implementations if neccessary or even use a DI container to wire them up and bypass the builders.