FileNotFound,当通过反射从加载的程序集中返回Types[]时
本文关键字:返回 集中 程序集 Types 程序 反射 加载 FileNotFound | 更新日期: 2023-09-27 18:00:36
我正在尝试加载一个加载项程序集(放置在
D: ''xyz''addin.dll
当我的应用程序在中时
D: ''MyApp''MyApp.exe
这样addin文件就不应该被锁定,以便在应用程序运行时可以再次复制它的新版本。为此,我创建了新的应用程序域,并加载了包含AssetLoader类的通用dll,然后调用AssemblyLoader加载加载项并获取其中所有可用的类型。加载项dll的依赖项已经放在同一文件夹中。现在从addin dll获取类型工作正常,但当我
返回组件。GetTypes();
一件非常奇怪的事情发生了。它执行该行,但在该函数退出时抛出异常"d:''xyz''addin.dll"FileNotFound
public class ObjectLoader : IDisposable
{
public Type[] GetAllTypesFromAssembly(string filePath)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
setup.ShadowCopyFiles = "true";
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AssemblyLoader asemblyLoader = null;
AppDomain appDomain = AppDomain.CreateDomain(filePath, adevidence, setup);
appDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
domains.Add(filePath, appDomain);
object[] parms = { filePath };
BindingFlags bindings = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;
try
{
asemblyLoader = (AssemblyLoader)appDomain.CreateInstanceFromAndUnwrap(
setup.ApplicationBase +
"Common.dll", "Common.AssemblyLoader",
true, bindings, null, parms, null, null, null
);
}
catch (Exception ex)
{
throw ex; // new AssemblyLoadFailureException();
}
object types = null;
if (asemblyLoader != null)
{
// On following line i am facing the error which occur on following line but when GetAllTypes exits.
types = asemblyLoader.GetAllTypes();
}
return (Type[])types;
}
}
internal class AssemblyLoader : MarshalByRefObject, IDisposable
{
private Assembly assembly = null;
public object GetAllTypes()
{
BindingFlags flags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public;
object types = null;
if (assembly != null)
{
try
{
// following line works fine and loads a type (it contains one class)
types = assembly.GetTypes();
}
catch (Exception)
{
types = new ObjectLoadFailureException();
}
}
else
{
types = new AssemblyNotLoadedException();
}
return types;
}
}
以下是异常详细信息:
System.IO.FileNotFoundException was unhandled
HResult=-2147024894
Message=Could not load file or assembly 'AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Source=mscorlib
FileName=AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
FusionLog==== Pre-bind state information ===
LOG: DisplayName = AddIn, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
(Fully-specified)
LOG: Appbase = file:///D:/MyApp/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
如果我在D:''xyz''和D:''MyApp''中复制我的addin.dll,则没有错误。我在运行时环境中无法做到这一点。
您正在将Type
对象编组到主AppDomain中
这会导致CLR加载包含该AppDomain中类型的程序集,从而导致此错误。
您可能根本不应该使用AppDomains。