简体   繁体   English

.NET - 无法为已加载的程序集加载文件或程序集

[英].NET - Could not load file or assembly for already loaded assembly

How does .NET resolve assemblies referenced by dynamically compiled in-memory assemblies. .NET 如何解析动态编译的内存程序集引用的程序集。

I'm hosting Razor view engine and using it to compile views on the fly, but am having problems getting it to reference the main project's assembly.我正在托管 Razor 视图引擎并使用它即时编译视图,但在让它引用主项目的程序集时遇到问题。 In the compile parameters I add a reference 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 runs fine, so long as I don't reference any types in the project DLL - in which case I get the following error:只要我不引用项目 DLL 中的任何类型,代码就可以编译并运行良好 - 在这种情况下,我会收到以下错误:

Could not load file or assembly 'MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.无法加载文件或程序集“MyProject,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null”或其依赖项之一。 The system cannot find the file specified.该系统找不到指定的文件。

I've double checked and this assembly is already loaded at the point where the exception is being thrown.我已经仔细检查过,这个程序集已经在抛出异常的地方加载了。 What am I missing?我错过了什么?

Figured it out.弄清楚了。 The main project is a dll loaded by an exe in a different directory.主项目是一个 dll 由不同目录中的 exe 加载。 .NET assembly loader by default searches the exe directory but not the dll's directory. .NET 程序集加载器默认搜索 exe 目录而不是 dll 的目录。 Resolved it with an AppDomain.CurrentDomain.AssemblyResolve event that searches the folder of the project dll.通过搜索项目 dll 的文件夹的 AppDomain.CurrentDomain.AssemblyResolve 事件解决了它。

From the code it appears as though you are creating a separate AppDomain to host the dynamically compiled in-memory assembly.从代码中可以看出,您正在创建一个单独的 AppDomain 来托管动态编译的内存中程序集。

It may be that your dynamically compiled assembly is referencing an assembly that your main app is not.可能是您的动态编译程序集引用了您的主应用程序不是的程序集。 See if casting your exception to ReflectionTypeLoadException and checking the LoaderExceptions doesn't provide a clue.查看将异常转换为ReflectionTypeLoadException并检查LoaderExceptions是否提供线索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM