2

我正在尝试动态加载一些这样的程序集:

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
}

但是,当调用 ctor 时出现异常,并且 CLR 尝试加载依赖程序集。我已在 for 循环中将依赖项加载到应用程序域中。我该如何解决这个异常?

  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: 
4

1 回答 1

8

我通过处理解决了类似的问题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);
}

这要求所有依赖项都已加载。

于 2013-03-11T23:47:38.617 回答