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 &&
      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)
  { = name;
    this.targetType = targetType;
  public object Resolve(IBuilderContext context)
    string setting = ConfigurationManager.AppSettings[];
    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()
                   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).

Auto-generated Factories with Unity

If you need to create objects after the initialization of your object graph by the container injecting factories is the way to go.

But defining factory interfaces and/or abstract base classes, implementing them and duplicating the knowledge your container already has does not make sense. For these scenarios Castle Windsor has it’s Typed Factory Facilities.

Define just the factory interface. Register it with the container and tell the container to generate an implementation for you. After all the implementation does not matter. Its a detail the consumers should not have to care about. If you need to forward runtime parameters like ConnectionStrings or file names the container takes care of that too.

With TecX.Unity.Factories you get the same set of features for Unity as well. All of a sudden using factories becomes as easy as this:

public interface IMyFactory
 IFoo Create(string name);
public interface IFoo
 string Name { get; }
public class Foo : IFoo
 public string Name { get; set; }
 public Foo(string name)
 this.Name = name;
var container = new UnityContainer();
container.RegisterType<IMyFactory>(new TypedFactory());
container.RegisterType<IFoo, Foo>();
var factory = container.Resolve<IMyFactory>();
var foo = factory.Create("some name");
Assert.AreEqual("some name", foo.Name);

This also works for property injection as long as you mark the property for injection by the container.

container.RegisterType<IFoo, Foo>(new InjectionProperty("Name"));

After a major overhaul of its internals the TypedFactory no longer relies on Castle DynamicProxy for the generation of the interface implementation. Unity brings its own powerful block for interception. It just insists that there has to be a target object for the interception pipeline. After integrating the technique used to generate lazy proxies auto-generating factories is now a Unity-only implementation.

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

Generate strongly typed factory delegates

Unity provides automatic factories (delegates in the form Func<T>) out of the box. TecX adds TypedFactories. And now you can also tell the container to generate strongly typed factory delegates for you. Imagine you have the following definition of a factory delegate:

public delegate IUnitOfWork UnitOfWorkFactory(bool isReadOnly);

And a consumer of the delegate that looks something like this:

public class Consumer
  private readonly UnitOfWorkFactory factory;
  public Consumer(UnitOfWorkFactory factory)
    this.factory = factory;
  public UnitOfWorkFactory Factory { get { return this.factory; } }
  // [...]

What’s inside the IUnitOfWorkinterface does not matter. Its implementation is more interesting:

public class UnitOfWork : IUnitOfWork
  private readonly bool isReadOnly;
  public UnitOfWork(bool isReadOnly)
    this.isReadOnly = isReadOnly;
  public bool IsReadOnly { get { return this.isReadOnly; } }
  // [...]

Notice that the name of the parameter the delegate takes equals the name of the constructor parameter of UnitOfWork.

The following test runs green.

var container = new UnityContainer();
container.RegisterType<UnitOfWorkFactory>(new DelegateFactory());
container.RegisterType<IUnitOfWork, UnitOfWork>();
Consumer consumer = container.Resolve();
UnitOfWork uow = consumer.Factory(true) as UnitOfWork;

That means that Unity generates a UnitOfWorkFactory delegate under the covers and injects it into the constructor of the Consumer class. The DelegateFactory also forwards the parameter you have to provide when calling the delegate.

So that’s yet another way not to write code for a factory.

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

Auto-generate NullObjects

NullObjects are a very usefull pattern. Among some other things they can be used as a means of defensive programming. If you have a dependency of a certain type (say ILogger) and don’t want make it an optional dependency using property injection (with the added downside of having to check for null every time you access that property) you can use a NullObject (in this case a NullLogger) to ensure that an instance of your interface is always present. Better prevent errors in the first place than telling people what they did wrong afterwards.

But do you really want to spend the time to implement classes that do … nothing?!

I consider DI containers (and infrastructure in general) a great tool to relieve programmers of the burden of routine tasks. Maybe that’s because I’m lazy and don’t want to do the same work twice.

A while ago Oren Eini announced a challenge for a Null Object Dependency Facility for Castle Windsor. I don’t know wether that challenge ever resulted in any actual code but I think its fun to solve that problem for Unity.

After some fiddling around with Reflection.Emit (again…) I am proud to announce that Unity can automatically generate and inject implementations even for trickier interfaces (like TryGetValue with out parameters). The generated code will never return null for strings or collections but empty strings and collections instead.

The functionality is accessible via an extension method for IUnityContainer.

public static IUnityContainer RegisterNullObject(this IUnityContainer container,
    Type contract, string name, LifetimeManager lifetime, 
    params InjectionMember[] injectionMembers)

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