Strange behavior when mixing assembly loading using Assembly.LoadFrom and Assembly.Load

Strange behavior when mixing assembly loading using Assembly.LoadFrom and Assembly.Load

I came across strange behavior when loading assemblies using Assembly.LoadFrom and later with Assembly.Load.
I load the assembly using Assembly.LoadFrom, where the assembly is in a folder that is not a runtime folder.

Later in my test code, when I try to load this assembly again from Assembly.Load, the load fails with System.IO.FileNotFoundException ("Could not load file or assembly ..."), even though the assembly is already loaded . The load does not work with either a strong name or a weak name (the original reason for reloading this assembly is to use a binary file).

However, if the assembly is in the execution folder, later loading will succeed in both cases with a strong name and a weak name. In this case, you can see that two identical assemblies are being loaded from two different places.

A simple example of code that recreates this problem is

Mounting Assembly1 = Assembly.LoadFrom (@ "C: \ a.dll");

// Loading with a strong name is not performed Assembly assembly2 = Assembly.Load (@ "a, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = 14986c3f172d1c2c");

// Also loading with a slight error Mounting assembly3 = Assembly.Load (@ "a");

  • Any explanation why the CLR ignores an already loaded assembly?
  • Any idea how I can solve this problem?

Thanks.

+5
source share
2

. , Load LoadFrom . .

  • , CLR ?

.

  1. , ?

CLR , , AppDomain.AssemblyResolve.

Alternative

, , AppDomain.BaseDirectory, 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

+9

@ : . , , , , : http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx

, 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;
 }
+7

All Articles