Assembly.LoadFrom fails when referencing Microsoft.EntityFrameworkCore.dll

119 Views Asked by At

While attempting to dynamically load libraries in to my .NET Core application, I seem to be running the following exception:

FileLoadException: Could not load file or assembly 'Microsoft.EntityFrameworkCore, Version=2.2.4.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. Could not find or load a specific file.

The stacktrace is pointing back to Assembly.LoadFrom, which is being called by the following custom event handler for AppDomain.CurrentDomain.AssemblyResolve

private Assembly LoadAssembly(string directory, string assemblyName)
{
  Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assemblyName);
    if (assembly != null)
      return assembly;

  Assembly result = null;
  var targetFile = System.IO.Path.Combine(directory, assemblyName.Split(',')[0] + ".dll");
  if (File.Exists(targetFile))
  {
    result = Assembly.LoadFrom(targetFile);
  }
  return result;
}

(Note, the event handler is technically a lambda which redirects to this method, hence the unusual signature)

The purpose of this callback is to resolve assembly references from a loaded plugin - by the time we get here, we have already called Assembly.LoadFrom successfully once.

The execution is clearly getting past the check of whether the file exists or not; however, I am unable to determine the reason why the load would fail.

The only possible cause I can determine is that it is hitting a similar validation to the following:

Starting with .NET Framework 4, the ability to execute code in assemblies loaded from remote locations is disabled by default, and the call to the LoadFrom method throws a FileLoadException.

From Microsoft Docs - .NET Framework Assembly.LoadFrom

However, the program doesn't fail on all loads, just the first load to this assembly. Specifically, two other assemblies succeed beforehand - one outside of the callback, and one inside the callback before trying to resolve Microsoft.EntityFrameworkCore.dll. I have confirmed this file exists in the target location.

Any recommendations on what is going on?

0

There are 0 best solutions below