TypedFactory reloaded

Another piece of code that I wrote some time ago came back to my attention recently and I decided to give it the same treatment as the SmartConstructor and do some cleanup on the TypedFactory port I did for Unity.

One thing I really disliked at the time was that the Unity Interception Extension cannot generate a “proxy without target” out of the box. If you want to intercept calls to an object you actually need to have that object. A pipeline with no target isn’t possible with Unity.

As I had experimented with IL code generation before I took the long way round and built a NullObject generator. Not pretty. But it worked.

Another issue was the need to fumble an instance of the container into the interception pipeline by putting it in a dictionary, retrieving it down the pipeline, cast it back to a container and then start working with it. For the life of me I couldn’t find an architecturally clean way to solve that issue then. But the ugly one worked.

If you can’t see the forest for the trees you need to take a step back. A year later I took a look at a post that I had read back then and all of a sudden the pieces fell into place.

As an answer to a question in the Unity discussion forum Chris Tavares solved both of my problems. I just didn’t get it the first time.

The code snippet to generate a proxy without a target (or more precisely an interception pipeline without a target) is really simple.

Intercept.NewInstanceWithAdditionalInterfaces(
  Type type,
  ITypeInterceptor interceptor,
  IEnumerable<IInterceptionBehavior> interceptionBehaviors,
  IEnumerable<Type> additionalInterfaces,
  params object[] constructorParameters)

 

This method gives us all that we need. The type parameter lets you specify the type of the target object. As we don’t actually need a target typeof(object) is good enough. The VirtualMethodInterceptor from Chris’ answer is what we will use as interceptor. The factory interface we want to implement goes into the additionalInterfaces. As our target is a simple object we don’t need to bother about constructorParameters.

The actual factory logic is implemented as an IInterceptionBehavior called FactoryBehavior (I’m all for self-explanatory names by the way). But that behavior still needs an instance of the container which is just not available at the place this is all wired up.

Again, Chris’ post gave me a solution that I just didn’t recognize.

Anyway, to hook it up to the container, the quickest thing to do would be to use InjectionFactory to call the Intercept.NewInstance API.

InjectionFactory is derived from InjectionMember (as is TypedFactory). InjectionMembers are Unity’s way to make very specific additions to the build pipeline of a type. An InjectionFactory tells the  container how to construct an object instead of letting the container figure out how to do that itself.

InjectionFactory has two constructors that each take a delegate that lets you specify how to create your object of interest.

I’ll just show you the signature of the greedier one of the two.

public InjectionFactory(Func<IUnityContainer, Type, string, object> factoryFunc)

The first parameter is a container out of the depths of the Unity infrastructure. And its totally for free. Below you see the new implementation of the AddPolicies(Type, Type, string, IPolicyList) method of the TypedFactory.

public override void AddPolicies(Type ignore, Type factoryType, string name, IPolicyList policies)
{
  if (factoryType.IsInterface)
  {
    InjectionFactory injectionFactory = new InjectionFactory(
      (container, t, n) => Intercept.NewInstanceWithAdditionalInterfaces(
        typeof(object),
        new VirtualMethodInterceptor(),
        new IInterceptionBehavior[] { new FactoryBehavior(container, this.selector) },
        new[] { factoryType }));

    injectionFactory.AddPolicies(ignore, factoryType, name, policies);
  }
  else if (factoryType.IsAbstract)
  {
    InjectionFactory injectionFactory = new InjectionFactory(
      (container, t, n) => Intercept.NewInstance(
        factoryType,
        new VirtualMethodInterceptor(),
        new IInterceptionBehavior[] { new FactoryBehavior(container, this.selector) }));

    injectionFactory.AddPolicies(ignore, factoryType, name, policies);
  }
  else
  {
    throw new ArgumentException("'factoryType' must either be an interface or an abstract class.", "factoryType");
  }
}

It supports interfaces and abstract classes as factoryType. Based on that distinction we either use the Intercept.NewInstanceWithAdditionalInterfaces or Intercept.NewInstance method to create our factory implementation. The container provided by the InjectionFactory gets forwarded into our FactoryBehavior and we are done. The rest of the implementation stays the same.

Now this is more like it. We reuse large parts of the Unity infrastructure instead of reinventing the wheel and quite a bit of code becomes obsolete. As usual you can find the code for the updated TypedFactory on my CodePlex site (project TecX.Unity[Factories] and the tests that show how it works under TecX.Unity.Test[Factories]).

Advertisement

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

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

Inject Primitive Dependencies by Convention

Mark Seemann, author of the book Dependency Injection in .NET, has a nice article about the injection of Primitive Dependencies.

From a technical perspective I find the part where he configures Castle Windsor to use his custom conventions most interesting. When I come across such a feature that exists in another DI container but is not present in Unity I try to port that feature. And I have yet to find some piece of functionality that cannot be implemented easily with a few lines of code. Adding support for parameter conventions takes about ~250 LoC. Due to the differences in their respective architecture the Unity implementation is two-part: The core part of the convention implements the custom interface IDependencyResolverConvention the part that performs the actual work implements IDependencyResolverPolicy which comes as part of the Unity infrastructure.

These are the interfaces:

public interface IDependencyResolverConvention
{
  bool CanCreateResolver(IBuilderContext context, DependencyInfo dependency);
  IDependencyResolverPolicy CreateResolver(IBuilderContext context, DependencyInfo dependency);
}

public interface IDependencyResolverPolicy : IBuilderPolicy
{
  object Resolve(IBuilderContext context);
}

Using that newly created infrastructure (and a second convention that works like the ConnectionStringConvention described in the article) you can resolve classes that look like these:

public class TakesPrimitiveParameter
{
  public int Abc { get; set; }
  public TakesPrimitiveParameter(int abc)
  {
    this.Abc = abc;
  }
}
public class TakesConnectionStringParameter
{
  public string AbcConnectionString { get; set; }
  public TakesConnectionStringParameter(string abcConnectionString)
  {
    this.AbcConnectionString = abcConnectionString;
  }
}

The integer value abc will be read from the appSettings section of your config file. The ConnectionString abc will be read from the connectionStrings section.

public class AppSettingsConvention : IDependencyResolverConvention
{
  public bool CanCreateResolver(IBuilderContext context, DependencyInfo dependency)
  {
    return dependency.DependencyType == typeof(int);
  }
  public IDependencyResolverPolicy CreateResolver(IBuilderContext context, DependencyInfo dependency)
  {
    return new AppSettingsResolverPolicy(dependency.DependencyName, dependency.DependencyType);
  }
}

public class AppSettingsResolverPolicy : IDependencyResolverPolicy
{
  private readonly string name;
  private readonly Type targetType;
  public AppSettingsResolverPolicy(string name, Type targetType)
  {
    this.name = name;
    this.targetType = targetType;
  }
  public object Resolve(IBuilderContext context)
  {
    string setting = ConfigurationManager.AppSettings[this.name];
    return Convert.ChangeType(setting, this.targetType);
  }
}

Setting up the registrations is as easy as this:

var container = new UnityContainer().WithDefaultConventionsForLiteralParameters();
var foo = container.Resolve<TakesPrimitiveParameter>();

Or if you prefer to have more fine granular control over the used conventions you can add them one by one:

var container = new UnityContainer()
                 .WithConventionsForLiteralParameters(
                   new ConnectionStringConvention(),
                   new AppSettingsConvention());
var foo = container.Resolve<TakesPrimitiveParameter>();

Neat and as Mark puts it: If you stick to your conventions it will just keep working when your code base grows.

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