将程序集加载到应用程序域,但收到无法加载文件或程序集异常
本文关键字:加载 程序集 文件 异常 应用程序域 | 更新日期: 2023-09-27 18:03:37
我正在尝试动态加载一些程序集,如:
using (var svc = new MyClient()) // MyClient is proxy to a WCF service
{
var bytecode = svc.GetAssembly();
var assembly = Assembly.Load(bytecode);
var dependencies = svc.GetDependencies();
foreach (var dependency in dependencies)
{
Assembly.Load(dependency.Bytecode);
Console.WriteLine("loaded {0}", asm.FullName);
}
var type = assembly.GetExportedTypes().First();
var ctor = type.GetConstructor(new Type[0]);
var obj = ctor.Invoke(new object[0]); // get an exception here
}
然而,当调用tor时,我得到一个异常,CLR试图加载依赖的程序集。我已经在for循环中将依赖项加载到app域中。如何修复此异常?
System.Reflection.TargetInvocationException occurred
HResult=-2146232828
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.ConstructorInfo.Invoke(Object[] parameters)
at MyClass.Program.Main(String[] args) in f:'Client'Program.cs:line 25
InnerException: System.IO.FileNotFoundException
HResult=-2147024894
Message=Could not load file or assembly 'Asm2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
Source=Asm1
FileName=Asm2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
FusionLog==== Pre-bind state information ===
LOG: User = mymachine'me
LOG: DisplayName = Asm2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
(Fully-specified)
LOG: Appbase = file:///f:/Client/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: f:'Client.vshost.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:'Windows'Microsoft.NET'Framework'v4.0.30319'config'machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///f:/Client/bin/Debug/Asm2.DLL.
LOG: Attempting download of new URL file:///f:/Client/bin/Debug/Asm2/Asm2.DLL.
LOG: Attempting download of new URL file:///f:/Client/bin/Debug/Asm2.EXE.
LOG: Attempting download of new URL file:///f:/Client/bin/Debug/Asm2/Asm2.EXE.
StackTrace:
at MyNamespace.MyClass..ctor()
InnerException:
我通过处理AppDomain.CurrentDomain.AssemblyResolve
解决了一个类似的问题:
AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
private static Assembly AssemblyResolve(object sender, ResolveEventArgs args)
{
return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == args.Name);
}