Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot load a reference assembly for execution from a Web-Site project

Using .NET 4.6.2 and an older Web-Site (not Web-Application) project. If I clear the BIN directory and then build and run it works, but sometimes after multiple builds and runs, it fails with this error.

Server Error in '/' Application.
Cannot load a reference assembly for execution.
....
[BadImageFormatException: Cannot load a reference assembly for execution.]
[BadImageFormatException: Could not load file or assembly 'netfx.force.conflicts' or 
one of its dependencies. Reference assemblies should not be loaded for execution.  
They can only be loaded in the Reflection-only loader context.
(Exception from HRESULT: 0x80131058)]
....

Is there any trick to getting Web-Site projects to work correctly when the libraries they use are beginning to pull in netstandard 2.0?

Also, it seems that this assembly binding redirect is necessary to get it to run but nuget adds a redirect to an older version 4.1.1.0. Any suggestions on how to fix that other than manually editing this line after most nuget updates?

  <dependentAssembly>
    <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a"
                      culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" />
  </dependentAssembly>

Would all these issues go away if the project was migrated to a Web-Application project?

like image 680
Ian Mercer Avatar asked Aug 30 '17 20:08

Ian Mercer


1 Answers

Most likely you are encountering this error because of a mismatch between x86 and x64 compiled assemblies or similarly a mismatch between .NET Framework and .NET Core.

Here are some troubleshooting options for you that you may not have tried.

Option #1

In the AppDomain there is an event handler for when the program is trying to resolve an assembly that is reference. If you subscribe to it, you should be able to get more information about what is missing. This is how the implementation would look:

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

Event Handler:

private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    System.Diagnostics.Trace.TraceInformation($"Trying to resolve assebly: {args.Name} requested by {args.RequestingAssembly.FullName}");
    // This event handler allows you to help the find the assembly for the CLR.
    // you can dynamically load the assembly and provide it here. 
    return null;
}

Option #2

There is also a tools in the .NET SDK for troubleshooting binding issues.

Here is more information about the Assembly Binding Log Viewer

You need to enable it before it will emit any interesting information, but this should get you to the root of your problem, if the AssemblyResolve event doesn't help.

like image 179
Glenn Ferrie Avatar answered Jan 02 '23 21:01

Glenn Ferrie