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

Fun with constructor arguments Part 3: Named registrations

A while ago there was a question on StackOverflow: If I have multiple implementations of an interface registered as named mappings and a constructor that should consume such a named mapping how can I tell Unity to automatically match the argument name to the mapping name?

E.g. if you have the following class definitions:

public interface ICommand { }

public class LoadCommand : ICommand { }

public class SaveCommand : ICommand { }

public class Consumer
{
  public Consumer(ICommand loadCommand, ICommand saveCommand)
  {
    // ...
  }
}

Now you setup your container and register both command implementations:

container.RegisterType<ICommand, LoadCommand>("loadCommand");
container.RegisterType<ICommand, SaveCommand>("saveCommand");

And when you resolve the Consumer the LoadCommand should be used for the parameter named loadCommand and the SaveCommand should be used for the parameter named saveCommand.

This is what you would have to do using Unity as is:

container.RegisterType<Consumer>(  new InjectionConstructor(
  new ResolvedParameter(typeof(ICommand), "loadCommand"),
  new ResolvedParameter(typeof(ICommand), "saveCommand")));

And this is a “slightly” enhanced version:

container.RegisterType<Consumer>(new MapParameterNamesToRegistrationNames());

The class MapParameterNamesToRegistrationNames is derived from InjectionMember. It places a marker policy in Unity’s build pipeline. When an object is resolved by the container a custom BuilderStrategy looks for that marker. If the marker is found the strategy will replace the dependency resolvers (implementations of IDependencyResolverPolicy) that Unity puts into the pipeline by default with NamedTypeDependencyResolvers using the name of the constructor argument as name of the mapping.

public class MapParameterNamesToRegistrationNamesStrategy : BuilderStrategy
{
  public override void PreBuildUp(IBuilderContext context)
  {
    if (context.Policies.Get(
      context.BuildKey) == null)
    {
      return;
    }
    IPolicyList resolverPolicyDestination;
    IConstructorSelectorPolicy selector =
      context.Policies.Get(
        context.BuildKey, out resolverPolicyDestination);
    if (selector == null)
    {
      return;
    }
    var selectedConstructor = selector.SelectConstructor(context, resolverPolicyDestination);
    if (selectedConstructor == null)
    {
      return;
    }
    ParameterInfo[] parameters = selectedConstructor.Constructor.GetParameters();
    string[] parameterKeys = selectedConstructor.GetParameterKeys();
    for (int i = 0; i < parameters.Length; i++)
    {
      Type parameterType = parameters[i].ParameterType;
      if (parameterType.IsAbstract ||
          parameterType.IsInterface ||
          (parameterType.IsClass && parameterType != typeof(string)))
      {
        IDependencyResolverPolicy resolverPolicy =
          new NamedTypeDependencyResolverPolicy(parameterType, parameters[i].Name);
        context.Policies.Set(resolverPolicy, parameterKeys[i]);
      }
    }
    resolverPolicyDestination.Set(
      new SelectedConstructorCache(selectedConstructor), context.BuildKey);
  }
}

The registration code tells you exactly what you expect from the container. No confusing setup of InjectionConstructors and ResolvedParameters. Just another simple convention that can make your life a lot easier.

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

Fun with constructor arguments Part 2: Anonymous overrides

An interesting feature of Castle Windsor is the ability to specify parameter overrides for a constructor using anonymous objects.

You define an anonymous object with properties named like the parameter you want to override and assign some value to it. You can either directly provide a value for that parameter or the name of a mapping you registered for the type of that parameter.

That means if you have a class with a dependency like this one:

public class MyService : IMyService
{
  public IFoo SomeFoo { get; set; }
  public MyService(IFoo someFoo)
  {
    this.SomeFoo = someFoo;
  }
}

and two classes that implement IFoo called Foo and Bar. Foo is registered as the default mapping (without a name) and Bar is registered as an additional mapping for IFoo with the name “Bar”:

container.RegisterType<IFoo, Foo>();
container.RegisterType<IFoo, Bar>("Bar");

You can use the AnonymousParameterOverride to specify that you want to use the named mapping instead of the default one:

container.RegisterType<IMyService, MyService>(new AnonymousParameterOverride(new  { foo = "Bar" });

Now this looks a little bit better than the default way Unity offers you to do this which is something like this:

container.RegisterType<IMyService, MyService>(
  new InjectionConstructor(new ResolvedParameter(typeof(IFoo), "Bar"));

But still not quite as fluent as I would like to see it. Unity does not really have a fluent configuration API but I took the liberty to write one.
The ConfigurationBuilder will be the subject of a series of posts on its own so for now let me just show you a glimpse at what is possible with it:

ConfigurationBuilder builder = new ConfigurationBuilder();
builder.For<IMyService>().Use<MyService>().Ctor(new { foo = "Bar" });

Much better isn’t it?

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

Fun with constructor arguments Part 1: Pick & Choose

One of Unity’s weaknesses is the verbosity of its configuration. While other containers support developers with various built-in conventions to keep the necessary setup code as compact as possible Unity requires you to state everything you want explicitely.

Consider the following skeleton of a class definition:

public class CustomerRepository
{
  public CustomerRepository(string connectionString, ILog log, ISomethingElse else) { ... }
}

Specifying the connectionString parameter for that constructor using Unity’s standard API looks like this:

container.RegisterType<ICustomerRepository, CustomerRepository>(
  new InjectionConstructor("I'mAConnectionString", typeof(ILog), typeof(ISomethingElse)));

There are a couple of things I don’t like about this approach:

  • Why do I have to write so much code to specify a single parameter?
  • Why do I have to specify all parameters although I care about only one?
  • Why does their order matter? Refactoring could break my registration code!
  • Why do I have to find out on my own that I can provide placeholders for parameters I don’t care about by providing their type?
  • Why do I have to provide those placeholders at all?

It’s all about verbosity. I don’t like to write unnecessary code. That is code I will have to write, test and maintain. The more effort I can save on that the better.

Conventions are a great means to not have to write code. They will get you 80% of the way most of the time at virtually no cost. And for the last 20% you can use the verbose API or define custom conventions that fit the special needs of your environment.

Providing a single parameter for the constructor of CustomerRepository can be as simple as this:

container.RegisterType<ICustomerRepository, CustomerRepository>(
  new SmartConstructor("I'mAConnectionString"));

What do you have to do to get that convenience? Not that much actually. SmartConstructor uses a couple of conventions to select a constructor from a set of candidates:

  • Only consider constructors that accept all provided parameters
  • Don’t consider constructors that have primitive parameters (like strings or integers) that are not satisfied by the provided parameters
  • If the parameter you specified is a string try to match it with parameters whose names contain connectionString, file or path.
  • Try to match specified parameters by parts of their type name. E.g. if you specified a parameter of type SomeTypeName a convention will look for parameters named someTypeName, typeName and name.
  • From the candidates that are left take the one with the most parameters (most greedy constructor).

The matching conventions are easy to write. They derive from ParameterMatchingConvention

public abstract class ParameterMatchingConvention
{
  public bool Matches(ConstructorParameter argument, ParameterInfo parameter)
  {
    ResolvedParameter rp = argument.Value as ResolvedParameter;
    Type argumentValueType = rp != null ? rp.ParameterType : argument.Value.GetType();
    if (argument.Value != null &&
        parameter.ParameterType.IsAssignableFrom(argumentValueType))
    {
      return this.MatchesCore(argument, parameter);
    }
    return false;
  }
  protected abstract bool MatchesCore(ConstructorParameter argument, ParameterInfo parameter);
}

That base class does some validation of the input values (which is omitted for brevity in the sample) and checks wether the type of the specified parameter matches the type of the parameter it is compared against. If that’s the case it hands over to the actual implementation of the convention. The ConnectionStringMatchingConvention for example looks as simple as that:

public class ConnectionStringMatchingConvention : ParameterMatchingConvention
{
  protected override bool MatchesCore(ConstructorParameter argument, ParameterInfo parameter)
  {
    if (parameter.ParameterType == typeof(string))
    {
      return parameter.Name.Contains("connectionString", StringComparison.OrdinalIgnoreCase);
    }
    return false;
  }
}

Done. To add a custom convention to the selection process you can call an extension method of IUnityContainer:

container.WithConstructorArgumentMatchingConvention(new MyCustomConvention());

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

Register mappings as group

A while ago there was a question on the Unity discussion forum on how to handle a set of mappings as a logical group.

By the time I was neither happy with the implementation nor the API of my proof-of-concept but recently I found some time to improve it.

Consider having interfaces IVehicle, IEngine and IWheel and implementations thereof like Car, MotorCycleWheel and the like. You want to use the MotorCycle* implementations when you ask the container for a motorcycle (via container.Resolve<IVehicle>(“Motorcycle”)). But you don’t want so setup InjectionConstructors or ResolverOverrides.

var container = new UnityContainer();
container.RegisterGroup(c =>
  {
    c.RegisterType<IVehicle, Car>("Car");
    c.RegisterType<IWheel, CarWheel>();
    c.RegisterType<IEngine, CarEngine>();
  });
container.RegisterGroup(c =>
  {
    c.RegisterType<IVehicle, Motorcycle>("Motorcycle");
    c.RegisterType<IWheel, MotorcycleWheel>();
    c.RegisterType<IEngine, MotorcycleEngine>();
  });

var car = container.Resolve<IVehicle>("Car");
Assert.IsInstanceOfType(car.Wheel, typeof(CarWheel));
Assert.IsInstanceOfType(car.Engine, typeof(CarEngine));

var motorcycle = container.Resolve<IVehicle>("Motorcycle");
Assert.IsInstanceOfType(motorcycle.Wheel, typeof(MotorcycleWheel));
Assert.IsInstanceOfType(motorcycle.Engine, typeof(MotorcycleEngine));

The RegisterGroup extension method takes an Action<IUnityContainer> where you can setup the mappings that belong together. The first mapping needs to be named so that the rest of the mappings in the group can be identified properly. After that the mappings are resolved as a whole.

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