Weird behaviour when mixing loading of assemblies using Assembly.LoadFrom and Assembly.Load

后端 未结 2 1984
广开言路
广开言路 2021-01-18 20:49

Weird behavior when mixing loading of assemblies using Assembly.LoadFrom and Assembly.Load

I have encountered a weird behavior when loading assemblies with Assembly.

相关标签:
2条回答
  • 2021-01-18 21:18

    @Kent Boogart: That appears to be the correct explanation. For a full explanation, Suzanne Cook has this blog post which elaborates a little more than the original one you posted: http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx

    Following is code leveraging AppDomain.AssemblyResolve -

     // register to listen to all assembly resolving attempts:
     AppDomain currentDomain = AppDomain.CurrentDomain;
     currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
    
    
     // Check whether the desired assembly is already loaded
     private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
        Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
        foreach (Assembly assembly in assemblies) {
           AssemblyName assemblyName = assembly.GetName();
           string desiredAssmebly = args.Name;
           if (assemblyName.FullName == desiredAssmebly) {
               return assembly;
           }
        }
    
        // Failed to find the desired assembly
        return null;
     }
    
    0 讨论(0)
  • 2021-01-18 21:42

    That's not weird. As per the documentation, loading with Load and LoadFrom will place the assemblies in different contexts. This might help.

    1. Any explanation why the CLR ignores the already loaded assembly?

    Because they're in a different context.

    1. Any idea how can I alleviate this problem?

    Load from the same context, or help the CLR find the assembly, perhaps by attaching a handler to AppDomain.AssemblyResolve.

    Alternative

    If the location you are loading assemblies from is a subfolder under AppDomain.BaseDirectory you can simply add an entry to your App.config:

    <configuration>
       <runtime>
          <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
             <probing privatePath="bin;bin2\subbin;bin3"/>
          </assemblyBinding>
       </runtime>
    </configuration>
    

    http://msdn.microsoft.com/en-us/library/823z9h8w.aspx

    0 讨论(0)
提交回复
热议问题