Settings Objects

Configurability is a member of the *-ability gang. Influence how your components work at runtime. Store configuration information somewhere. Either in code, in a config file or in some type of database. Load it at runtime and use it in your application.

You can hard-code the way these values are retrieved directly in your components. But that makes these components hard to test and limits your flexibility (another gang-member) later in the process. You can hand them to your component one-by-one either as constructor parameters or method parameters which tends to get very noisy if you need more than a few values. The Parameter Object Refactoring can reduce that noise a lot. Yet it does not solve the problem of how to get the values into that parameter object.

You can use some custom ConfigurationManager or extend the .NET configuration engine. But what about defining defaults for your configuration? Defaults for different scenarios maybe? Meaningful defaults can greatly reduce the clutter in your configuration.

I found another approach very useful: Encapsulate the way your configuration values are retrieved along with the defaults into something I call Settings Objects.

They contain a number of public virtual properties that are used to retrieve the desired configuration values.

public class DemoSettings
  private static class Defaults
    public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30);
  public virtual TimeSpan Timeout
      string key = GetKeyFor(() => Timeout);
      string valueFromConfigFile = ConfigurationManager.AppSettings[key];
      TimeSpan ts;
      if (!string.IsNullOrEmpty(valueFromConfigFile) &&
          TimeSpan.TryParse(valueFromConfigFile, CultureInfo.CurrentCulture, out ts))
        return ts;
      return Defaults.Timeout;
  private string GetKeyFor(Expression<Func> memberSelector)
    MemberExpression expression = (MemberExpression) memberSelector.Body;
    string key = this.GetType().Name + "." + expression.Member.Name;
    return key;

The code in this demo tries to load configuration values from a config file following an easy convention: Values are stored as <NameOfTheSettingsClass>.<PropertyName> in the appSettings section.

If no value is found or the value does not meet the format expectations a hard-coded default is used. If performance is critical you can use a private member or any kind of cache to store the retrieved value. You can implement expiration for your cached values if you want to.

If you derive from DemoSettings you can use different default values in your derived classes. Or you can entirely hard-code values. Which is especially useful for testing scenarios. Or you can turn that procedure upside-down and design a base-class that uses hard-coded values (e.g. in the beginning of the development of a new component) and derive settings objects with different methods for information retrieval later as needed.

You can read from a database instead of a config file. Or you can implement a “three strikes” scenario: Check wether the value is defined in your local config file. If not check the database. If there is no value in the database use the default. By this, values in a config file override values in a database which in turn override the hard-coded defaults.

Btw.: If you are using a database caching might make sense to avoid too many round-trips. And if you are already on .NET 4.5 you can use the CallerMemberNameAttribute instead of an Expression to figure out the name of the property you want to retrieve.

You can argue that Settings Objects violate the Single Responsibility Principle and I agree with you. A settings DTO and a separate Loader class of some kind are more SRP’ish. But in this case I value the improved useability of settings objects more than following SRP. They are small, self-contained objects. If you don’t need the additional configurability stick with hard-coded values. That minimizes the effort until you really have a need for that flexibility (and someone is willing to pay you for it). You don’t have to write another “framework” to fill your settings objects with values from various sources. You can decide on a case-by-case basis wether you need support for config-files or databases or something else or if hard-coded values are good enough for now. I like this approach and it served me well on several projects.


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();

      new FormatterBuilder()
        .UsingTemplate("{timestamp} {message}"));

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.

Testing HttpHandlers

For experienced web-developers this post will not bring any news but I hope beginners in Microsoft web technologies (like myself) will find it helpful.

Recently I started to work on a web project where I have to deal with custom HttpHandlers. They implement the IHttpHandler interface which looks like this:

public interface IHttpHandler
  bool IsReusable { get; }
  void ProcessRequest(HttpContext context);

The problem is the single parameter of the interface’s ProcessRequest method. It’s really hard to work with HttpContext in unit tests. Mocking request or response properties is almost impossible and feeding them the right data is also non-trivial.
Microsoft noticed that as well some time in the past and offered an abstract base class called HttpContextBase which looks (almost) exactly like the original HttpContext but lets you override each and any property or method to return your desired values. But although the name suggests otherwise HttpContext does not derive from HttpContextBase. So what’s the use of it anyway?!?

There is a third class called HttpContextWrapper (derived from HttpContextBase) which wraps an instance of the HttpContext and serves as an adapter to the API provided by HttpContextBase.

So now we have an adapter for the real thing we can implement a custom handler like this:

public class MyHttpHandler : IHttpHandler
  void IHttpHandler.ProcessRequest(HttpContext context)
    Guard.AssertNotNull(context, "context);
    HttpContextBase wrapper = new HttpContextWrapper(context);

  public void ProcessRequest(HttpContextBase context)
    // ... do your magic here

We still can’t test the implementation of IHttpHandler.ProcessRequest directly. But I’m positive that Microsoft invested some work into the HttpContextWrapper so I think it’s safe to assume that it works as expected. And the three lines in that implementation are really trivial enough to exclude them from our test suite without bad conscience.

So what do we gain? Testing ProcessRequest(HttpContextBase) is a piece of cake now that we can manipulate the data served by a mock implementation of HttpContextBase. By that we can simulate input conditions that would be hard to fake using an instance of the real HttpContext.

Btw.: There are abstractions for other concrete classes from System.Web like HttpApplicationState, HttpResponse, HttpRequest or HttpServerUtility and many more.

Enum support for Unity

Today I stumbled upon a question on StackOverflow that was related to the resolution of an enum-Type dependency using StructureMap.

And I thought to myself: Can Unity handle enums? Turns out it can’t. But yet again the flexible architecture allows you to retrofit that feature with ease.

First we need a strategy that detects when we are trying to resolve an enum-Type:

public class EnumStrategy : BuilderStrategy
  public override void PreBuildUp(IBuilderContext context)
    if (context.BuildKey.Type.IsEnum && context.Existing == null)
      IBuildPlanPolicy policy = new EnumPolicy(context.BuildKey.Type);
      context.Policies.Set(policy, context.BuildKey);

If the requested Type is an enum we place an IBuildPlanPolicy in the policy list that knows how to create the default value of that enum-Type.

public class EnumPolicy : IBuildPlanPolicy
  private readonly Type enumType;
  public EnumPolicy(Type enumType)
    this.enumType = enumType;
  public void BuildUp(IBuilderContext context)
    if (context.Existing == null)
      context.Existing = Enum.ToObject(this.enumType, 0);

We show some manners and make sure that there is no value inside the BuilderContext before we fill in the enum value.
And finally we need an extension that installs the strategy in the pipeline:

public class EnumExtension : UnityContainerExtension
  protected override void Initialize()
    var strategy = new EnumStrategy();
    this.Context.Strategies.Add(strategy, UnityBuildStage.PreCreation);

Where another test proves that Unity’s default behavior is to throw a ResolutionFailedException when it is asked to resolve an enum-Type dependency now the following test runs green:

public void CanResolveDefaultEnumValueForByteBasedEnum()
  var container = new UnityContainer().AddNewExtension();
  var sut = container.Resolve<DependsOnEnumBasedOnByte>();
  Assert.Equal(EnumBasedOnByte.Default, sut.Enum);

As the names of the test classes indicate this also works for enum-Types that are not derived from integer. Problem solved.

Get the source code for the EnumExtension  here (project TecX.Unity folder Enums and the test suite that shows how to use it in TecX.Unity.Test).