Problem building up types created with Castle DynamicProxy

Jun 12, 2009 at 6:29 AM
Edited Jun 12, 2009 at 6:31 AM

I'm having a problem with some unit tests that need to add mocked interface implementations to a Unity container.
After digging around for a while I have boiled down the problem to Castle DynamicProxy not giving constructor parameters names on generated proxy types.

Here is the most minimal program that can replicate the issue:

    using Castle.DynamicProxy;
using Microsoft.Practices.Unity;
public static class Program
public static void Main()
var unity = new UnityContainer();
var gen = new ProxyGenerator();
var test = gen.CreateInterfaceProxyWithoutTarget<ITest>();
unity.BuildUp(test); //works
unity.BuildUp(test.GetType(), test); //error!
public interface ITest {}

I realise that it's better to use the first BuildUp<T> overload from my example above, but the framework I have to work with uses the second one.
Here is the exception stack trace:

    System.ArgumentNullException: Value cannot be null. Parameter name: str
       at System.Reflection.Emit.DynamicILGenerator.Emit(OpCode opcode, String str)
       at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context)
       at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
       at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, Object buildKey)
       at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
       at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
       at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp(IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
       at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
       at Microsoft.Practices.Unity.UnityContainer.BuildUp(Type t, Object existing, String name)
       at Microsoft.Practices.Unity.UnityContainerBase.BuildUp(Type t, Object existing)
       at Experimentation.Program.Main()

I think the solution could be as simple as changing line 80 of DynamicMethodConstructorStrategy.cs from
    buildContext.IL.Emit(OpCodes.Ldstr, parameters[i].Name);
    buildContext.IL.Emit(OpCodes.Ldstr, parameters[i].Name ?? "P" + i);
and line 194 from
    parameters[i].Name ?? "P" + i);

That way unnamed parameters are handled correctly.