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).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: