From Static to Flexible

Back in the “good old days” static classes and singletons where widely used patterns. They could be called from anywhere and you didn’t have to spend a thought on dependency management. Or unit testing. Because most often you couldn’t test code that called methods on those objects. They usually needed config files, databases, web-services, message queues, more files, network shares … just about anything. And none of that plays nice with unit tests. Pity that these days can also be called “earlier this year”…

As a “tame” example of such a static object think of the File class. Now imagine you have a component that uses File.Exists(). How do you test that code? Do you really want to create a file whenever you try to run a test of your component?

Lets look at a sample to show how you can still test that code.

public class MyComponent
{
  public void DoIt(string pathToFile)
  {
    if(File.Exists(pathToFile)) { /* ... */ }
    else { /* ... */ }
  }
}

In order to simulate the situation where the file exists you would have to create said file. That’s not what unit tests are for. They should be almost effortless to write. Wrestling with the file systen in a unit test scenario is definitely not effortless.

A common recommendation is to write a wrapper for the File class which is non-static. That would look like this:

public class FileWrapper
{
  public bool Exists(string path)
  {
    return File.Exists(path);
  }
}

But that’s not the whole story. We need a way to simulate the result of FileWrapper.Exists() or we would just add code but won’t gain anything. To do that we lend ourselves the solution Microsoft used for HttpContext. We introduce a base class with all virtual properties and methods.

public class FileBase
{
  public virtual bool Exists(string path)
  {
    throw new NotImplementedException();
  }
}
public class FileWrapper : FileBase
{
  public override bool Exists(string path)
  {
    return File.Exists(path);
  }
}

Now we change our component to use some instance of FileBase instead of the static File class.

public class MyComponent
{
  private readonly FileBase file;
  public MyComponent(FileBase file)
  {
    this.file = file;
  }
  public void DoIt(string pathToFile)
  {
    if(this.file.Exists(pathToFile)) { /* ... */ }
    else  { /* ... */ }
  }
}

We can use Moq or some hand-crafted test double that implements FileBase to simulate the existance or non-existance of said file very easily.

To make things a bit nastier imagine that MyComponent is used throughout a large legacy codebase. You just changed the signature of it’s constructor. Now you would have to change all calls to that constructor immediately or the system will be broken. That’s not an option.

But if we add a constructor overload that delegates to the constructor we just created and uses the default implementation for FileBase we can leave all calls to the default constructor in place but still have the improved testability of the constructor that follows the Dependency Injection Pattern.

public class MyComponent
{
  private readonly FileBase file;
  public MyComponent() : this(new FileWrapper())
  {
  }
  public MyComponent(FileBase file)
  {
    this.file = file;
  }
  // more code
}

I know that this solution is not pure. The DI Pattern advocates the usage of one constructor only that takes all the dependencies of a class. I prefer that as well. But “legacy enterprise systems” are rarely what I’d call clean and sometimes you have to take some dirty intermediate steps towards clean solutions. With the technique outlined above you can improve such systems one step at a time. You can control how far these improvements are visible by adding or removing constructors that create default implmentations for their dependencies and replacing calls to these default constructors one at a time. Rome wasn’t built in a day…

Advertisements

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

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.

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:

[Fact]
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).

Register multiple instances without naming them

The wishlist for Unity vNext contains an item with the following description:

Register multiple instances without naming them and then resolve all these instances by ResolveAll

Well that does not sound that difficult does it? You just need to mess a little with Unity’s type mapping system.

Lets write a test first that will show we got it right:

[TestMethod]
public void CanResolveMultipeDefaultMappingsUsingResolveAll()
{
  var container = new UnityContainer().AddNewExtension<Remember>();
  container.RegisterType<IFoo, One>();
  container.RegisterType<IFoo, Two>();
  container.RegisterType<IFoo, Three>();
  IFoo[] foos = container.ResolveAll<IFoo>().OrderBy(f => f.GetType().Name).ToArray();
  Assert.AreEqual(3, foos.Length);
  Assert.IsInstanceOfType(foos[0], typeof(One));
  Assert.IsInstanceOfType(foos[1], typeof(Three));
  Assert.IsInstanceOfType(foos[2], typeof(Two));
}

Armed with the Unity source code I started digging for the truth.

The call to ResolveAll uses an internal class called NamedTypeRegistry to find out which mappings where registered as named mappings. You can’t access this class directly but the ExtensionContext that is provided to every class derived from UnityContainerExtension can add mappings to the registry. The code for the Remember extension does just that. Add a mapping to the registry and add another BuildKeyMappingPolicy that maps the named mapping to one of the default mappings.

public class Remember : UnityContainerExtension
{
  protected override void Initialize()
  {
    this.Context.Registering += this.OnRegistering;
    this.Context.RegisteringInstance += this.OnRegisteringInstance;
  }
  private void OnRegisteringInstance(object sender, RegisterInstanceEventArgs e)
  {
    if(string.IsNullOrEmpty(e.Name))
    {
      string uniqueName = Guid.NewGuid().ToString();
      this.Context.RegisterNamedType(e.RegisteredType, uniqueName);
      this.Context.Policies.Set<IBuildKeyMappingPolicy>(
        new BuildKeyMappingPolicy(new NamedTypeBuildKey(e.RegisteredType)),
        new NamedTypeBuildKey(e.RegisteredType, uniqueName));
    }
  }
  private void OnRegistering(object sender, RegisterEventArgs e)
  {
    if (e.TypeFrom != null && string.IsNullOrEmpty(e.Name))
    {
      string uniqueName = Guid.NewGuid().ToString();
      this.Context.RegisterNamedType(e.TypeFrom, uniqueName);
      if (e.TypeFrom.IsGenericTypeDefinition && e.TypeTo.IsGenericTypeDefinition)
      {
        this.Context.Policies.Set<IBuildKeyMappingPolicy>(
          new GenericTypeBuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
          new NamedTypeBuildKey(e.TypeFrom, uniqueName));
      }
      else
      {
        this.Context.Policies.Set<IBuildKeyMappingPolicy>(
          new BuildKeyMappingPolicy(new NamedTypeBuildKey(e.TypeTo)),
          new NamedTypeBuildKey(e.TypeFrom, uniqueName));
      }
    }
  }
}

And you are done. The associated test project assures that lifetimes and InjectionMembers are also respected as well as registered instances are reused. As a nice side effect a call to ResolveAll will now return all instances of all mappings including the default mapping which is otherwise omitted by Unity.

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

It depends Part 1: Contextual Binding

NInject has a very nifty feature called Contextual Binding. It allows users to define in which context to use a specific type mapping. With NInject that is completely baked into the container out-of-the-box. With Unity you need to do some pull-ups to get it.

First you need to capture the neccessary information from Unity’s build pipeline. Which type was originally requested? What is the target for the object that is currently resolved by the pipeline? What dependencies need to be resolved to be able to create the requested object? How to deal with short-circuits in the build pipeline e.g. when an object has a singleton lifetime? What about out-of-band resolves e.g. when you use InjectionFactories where an instance of IUnityContainer is injected?

This is done by a set of custom BuilderStrategies. They are also used to create the hierarchy of requests. If for example you want to create an instance of Foo that has a dependency on an implementation of IBar that needs an ILog which … well, you get it. The hierarchy of those requests must somehow be represented in the structure of the captured information.

What you get

TecX’ implementation mimics that of NInject to a certain degree. Due to the many differences between those two containers it cannot be a 1:1 port though. This is what TecX’ IRequest looks like:

public interface IRequest
{
  IBuilderContext BuilderContext { get; }
  int Depth { get; }
  IRequest ParentRequest { get; }
  IDictionary<string, object> RequestContext { get; }
  Type Service { get; }
  ITarget Target { get; }
  NamedTypeBuildKey BuildKey { get; }
  NamedTypeBuildKey OriginalBuildKey { get; }
  IRequest CreateChild(Type service, IBuilderContext context);
}

It allows access to infrastructure information like the original BuildKey of the request. The BuildKey after Unity performed the type mapping. The Target property tells you into which target the resolved value will be injected (can either be a parameter of a constructor or method or a property). The parent request, if the current request was made to resolve a sub-dependency. How deep down in the resolve hierarchy we are etc.

The implementation class Request provides access to the current request via the static Current property.

More context

You can register additional context information via the (also static) property StaticRequestContext which is a simple key/value store of type IDictionary<string, object>. This property is important for another feature that uses the contextual binding and will be presented in a later post.

As you can see in the code snippet above IRequest also has a RequestContext property. This can be used to store ‘per request’ information that will be shared throughout a single request but is lost at the end of that request. I decided to go for some more convenience and provide a custom implementation of IDictionary<TKey, TValue> that lets you access values from both the static and the per request context in a read through manner. Per request information has precedence over static information. If no per request information with that key is found the lookup is done on the static context next. If you add some values to the dictionary using IRequest.RequestContext this information will only be added to the per request context.

How to use it

There are several extension methods for IUnityContainer. Below you can see the signature of the method taking the most parameters:

public static IUnityContainer RegisterType(this IUnityContainer container,
  Type @from, Type to, LifetimeManager lifetime,
  Predicate predicate, params InjectionMember[] injectionMembers)

It allows you to specify source and target types for the mapping, the lifetime for the created object, a predicate that is validated to find out when to apply the mapping and a set of optional InjectionMembers where you can specify things like constructor to use, interceptors and much more. Overloads of that method add generic registrations, default lifetime etc.

[Teaser] The contextual binding features are also incorporated into TecX’ enhanced fluent configuration API.

This API lets you do the following:

var builder = new ConfigurationBuilder();
builder.For().Use().When(request => { /* ... */ };

or this:

builder.For<IFoo>().Use<Foo>().WhenInjectedInto<Parent>();

[/Teaser]

TecX’ Contextual Binding gives you more fine grained control over your type mappings than simple named mappings do. It also allows you to build far more readable registrations than with nested InjectionConstructors and ResolvedParameters.

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

Fun with constructor arguments Part 2.1: Anonymous overrides revisited

After publishing the post on Anonymous overrides I thought about the topic again. In the end it didn’t make sense to put that functionality in a separate class.

The SmartConstructor already does most of the heavy lifting and matching the properties of an anonymous object to constructor parameters can easily be encapsulated in a new ParameterMatchingConvention.

As a result the SmartConstructor grew by a few lines of code (reading the properties of the anonymous object and converting them to ConstructorParameters) and I created a new convention called StringAsMappingNameMatchingConvention.

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