Getting ReflectionTypeLoadException on 2nd attempt at reflection in .net 4
In my project I have the following helper method, which goes through all the assembly and gets all types that are subclasses of the BaseCamaFrom type.
public static List<Type> GetAllTestActionFormTypes()
{
List<Type> types = new List<Type>();
// add all the types that are subclasses of BaseCamaForm to the _camaFormType list
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
foreach (Type t in asm.GetTypes())
if (t.IsSubclassOf(typeof(BaseCamaForm)))
types.Add(t);
return types;
}
This method works correctly on the first call. However, u开发者_运维技巧pon calling this method a second time the following exception occurs when the asm.GetTypes()
is called:
ReflectionTypeLoadException was unhandled by user code: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Upon looking at the LoaderException property I found a System.IO.FileLoadException
with the following message:
Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
Why does this code work the first time it is called but always exceptions the second time?
Edit: After more investigation, the only assemblies I reference that have a Runtime Version of 2.0.50727 are Microsoft.TeamFoundation.Client and Microsoft.TeamFoundation.VersionControl.Client. I cannot figure out why these references are causing issues with reflection, nor why it seems to happen only on the 2nd attempt. This seems to sporadically also occur as well when attempting to use the
Activator.CreateInstance(types[x])
call on some classes.Apparently I had to add <startup useLegacyV2RuntimeActivationPolicy="true" />
into my app.config file. Once I did that I no longer had reflection exceptions occurring. I still don't know why it did this but at least it's fixed.
精彩评论