.NET Failed to load file or assembly for already loaded assembly.

How .NET resolves assemblies referenced by dynamically compiled assemblies in memory.

I host the Razor viewer and use it to compile views on the fly, but I have problems with its link to the main assembly of the project. In the compilation options, I add a link to the project assembly, something like this:

// Add references to all currently loaded assemblies foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { compileParams.ReferencedAssemblies.Add(a.Location); } 

The code compiles and works fine if I do not refer to any types in the project DLL - in this case I get the following Error:

Failed to load file or assembly "MyProject, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null" or one of its dependencies. The system cannot find the specified file.

I checked twice, and this assembly is already loaded at the time the exception is thrown. What am I missing?

+4
source share
2 answers

Figured it out. The main project is a dll loaded by exe into another directory. The .NET assembly collector by default looks for the exe directory, but not the dll directory. This is resolved with the AppDomain.CurrentDomain.AssemblyResolve event, which searches for the project DLL folder.

+2
source

From the code, it seems that you are creating a separate AppDomain to place the dynamically compiled assembly in memory.

Perhaps your dynamically compiled assembly refers to an assembly that your main application does not have. See if your exception is distinguished by the value of ReflectionTypeLoadException and the LoaderExceptions check LoaderExceptions not give a hint.

+1
source

All Articles