Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting ExecutionEngineException on .Net 4.0 Assembly.GetCustomAttributes after installing VS2012/.Net 4.5?

As simple as title really. I've upgraded a solution from .Net 2-3.5 to .Net 4, it worked fine, I've then installed VS 2012 and with it .Net 4.5 and I'm now getting an ExecutionEngineException when trying to reflect the CustomAttributes from a dynamically generated DLL using the following code:

Assembly assembly = Assembly.LoadWithPartialName("DavesNamespace.Custom");
var attributes = assembly.GetCustomAttributes(typeof(ChecksumAttribute), true);

I get the exception with or without the Type specified for GetCustomAttributes, but it's only at that point that it throws the exception, the assembly is successfully loaded and I can actually view the CustomAttributes collection if I stick a break point in.

The original .Net 2-3.5 version still works since having installed vs2012.

Any help much appreciated, I have found a few issues stemming from vs2012 ending with ExecutionEngineExceptions looking online, but nothing with an answer. The problem can be resolved by removing VS2012 and .Net 4.5, but as we're intending to move to VS2013 company wide when it's released that's not really a solution.

EDIT: Have got the error occuring in a sample app which does just this, and the exception is still thrown even if the application is built targetting 4.5

Stack trace added in the comments below (It's null)

like image 374
mckjerral Avatar asked Jul 23 '13 15:07

mckjerral


1 Answers

I have resolved the issue for our particular situation, although I think the root is an undocumented change in how .Net 4.5 reads CustomAttributes on DLLs.

The solution was moving a CustomAttributeBuilder being set from being the last thing before AssemblyBuilder.Save() [After all the content of the assembly has been populated] to the first thing after AppDomain.CurrentDomain.DefineDynamicAssembly() [Before any of the content has been populated]

The actual code where the exception was being thrown hasn't needed to change, although I have refactored to use the replacement for LoadWithPartialName() which is just Load(), this workaround still worked with LoadWithPartialName() though.

It may be that adding a custom attribute after the content of the assembly puts the custom attribute in the wrong place? But the issue is logged with MS to look into.

like image 193
mckjerral Avatar answered Oct 14 '22 06:10

mckjerral