BadImageFormatException when debugging interface mocked with RhinoMocks

My last couple of days has been quite hilarious. First there was the issue with not being able to set breakpoints on my tests, and then started having tests that failed one way when executed normally and a different way when I ran them with debugger attached!


The Problem


Recently I updated the project I am working on to Castle.Windsor version 2.1. Since we are using an abstraction over the container (for resolving purposes only), we had to adapt it to conform with the new restrictions for Resolving dependencies, thus:

public interface IFaroContainer 
    object Resolve(Type type);  
    object TryResolve(Type type);  
    IEnumerable ResolveAll(Type type);  
    void RegisterTypeIfMissing<TI, T>(bool registerAsSingleton) 
where T : class, TI;
object BuildUp(Type type); }

With the new Castle.Windsor version we have to enforce that our T class implements TI, which makes perfect sense and helps reducing erroneous registration issues that one could perform.

The problem is that when we try to Mock this interface (I am currently using RhinoMocks v3.6) while in debug mode we get a BadImageFormatException:

The problem is that there is a bug in the System.Reflection.Emit

implementation which cause the runtime to emit invalid code for this


You can read more here.


How I fixed my issue


Since I am depending on third party lib Castle.Windsor, I cannot change the way the fluent interface is designed. It seems though that this constraint is enforced only by Castle.Windsor’s fluent interface, if you use standard component registration you will be able to bypass that argument check thus not unleashing the Emit bug.

I just changed my registrations from using the fluent interface to use the traditional AddComponent and the tests started passing!

Shout it kick it on

5 thoughts on “BadImageFormatException when debugging interface mocked with RhinoMocks

  1. Pingback: DotNetShoutout
  2. @Krzysztof Koźmic
    True, my fault! I had the idea that I was using the version without the ILmerge of Castle assemblies, but I have noticed now that Rhino.Mocks 3.6 only has a version with merged assemblies.

    I got latest code from git-hub and checked that the version they are merging is in fact DP 2.1.

    Thank you so much for your support on this! 😉

Leave a Reply

Your email address will not be published. Required fields are marked *