AppDomain.CurrentDomain.GetAssemblies fails with ReflectionTypeLoadException

南笙酒味 提交于 2020-01-02 03:28:07

问题


During unittesting I have run into a problem with the following code that asks for all the loaded assemblies:

var res = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.ToList();

this code fails with a ReflectionTypeLoadException which has inner exceptions of the pattern

Could not load type Microsoft.Xml.Serialization.GeneratedAssembly.FOO

where FOO are some specific classes also coded by us.

The problem arises when running unittests prior to the above which creates XML documents using the XDocument class.

I may not necesarilly want to load these code generated classes (I'm guessing Microsoft.Xml.Serialization.GeneratedAssembly.* is code generated.) I just want to understand whats wrong.


回答1:


You should check IsDynamic field of your assembly which is availabe at .netframework 4 and later.

var res = AppDomain.CurrentDomain.GetAssemblies().Where(ass => ass.IsDynamic == false)
.SelectMany(x => x.GetTypes())
.ToList();



回答2:


Can you turn on Fusion log to see why are the Assemblies failing to load?

How to enable assembly bind failure logging (Fusion) in .NET




回答3:


I ended up concluding that the classes that are run-time code generated for serialization and xmlserialization (and others?) are uninterestingto me. Thus the following filter helped

return AppDomain.CurrentDomain.GetAssemblies()
.Where(x => !x.FullName.StartsWith("Microsoft.GeneratedCode"))
.SelectMany(x => x.GetTypes())
.ToList();


来源:https://stackoverflow.com/questions/19024826/appdomain-currentdomain-getassemblies-fails-with-reflectiontypeloadexception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!