2

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?

Serge
  • 1,974
  • 6
  • 21
  • 33
  • Please note, I won't be using this pattern moving forward with the project; however, it was a question that was unresolved. – Serge May 14 '19 at 04:48
  • 1
    have you had any solution for this yet? I'm encountering almost the same kind of issue (exactly that same kind of exception against loading Microsoft.EntityFrameworkCore using Assembly.LoadFrom), not sure if it's different in the cause. – Hopeless May 25 '19 at 12:56
  • 1
    Sorry, but I never did. I've moved on towards organizing my program differently. – Serge Jun 01 '19 at 15:25

0 Answers0