.NET 4.5 : Operation could destabilize the runtime (yikes!)
Update: Microsoft has since posted an update to .NET Framework 4.5 which resolves this issue. For more information, please visit http://support.microsoft.com/kb/2748645
The other week I got around to installing Visual Studio 2012 and .NET Framework 4.5 RTM bits on my machine – thought it was about time that I made the switch. Though after the installation I started getting a failing test in the Nancy test suite that said
Now I don’t know about you, but “Operation might destabilize the runtime” doesn’t sound like test best of things that could happen.
Following along the debugger for a ride though the code, I ended up at a line that performed an Activator.CreateInstance call on a type that was inheriting from AbstractValidator<T> from the (awesome) FluentValidation library. Code that hadn’t been changed in quite a while.
I was certain that this test didn’t fail prior to the upgrade and we had not updated out FluentValidation reference to a newer version. The test was failing in both Visual Studio 2010 and 2012, using both the TestDriven.NET and ReSharper Test Runner, so it had to be related to .NET 4.5 upgrade.
Even though the code was targeting the .NET Framework 4.0 it was still happening. Why is that? Well remember that 4.5 does not install side-by-side of 4.0, but instead it’s a drop-in replacement that is supposed to (there are some kinks to be worked out still) be backwards compatible. So even though you target 4.0, you are still running on the 4.5 runtime.
Luckily I was connected to Lee Coward on the CLR team and he was able to shed some light on the issue
The problem happens whenever the IL that the C# compiler emits for a derived class constructor contains one or more branches that appear before the call to the base class constructor.
So the problem exists on the IL level and is only detected when the CLR Verifier is executed on the code. The verifier makes sure that the IL is type safe before it’s sent to the JIT Compiler and if it detects and issue (like this) it will bark at you.
Furthermore, the constructor of the derived class has to be generic for all of this to happen. When these criteria are met, then there are quite a few scenarios that can cause the bug to be invoked.
Instead of trying to explain all of these, and possibly get any of the details wrong, I will share the sample that Lee Coward gave me
I’ve been told that they are working on a proper fix for this and also on guidance on which C# code patterns that will cause the verification error.
In the meantime I’ve submitted a pull-request to FluentValidation that resolves that prevents it from causing the verification errors and Jeremy Skinner has already put out a new version on Nuget. So if you are experiencing issues with .NET 4.5 and FluentValidation all you have to do is update to the newest version