C# 加载程序集及其依赖项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading assemblies and its dependencies
提问by FantaMango77
My application dynamically loads assemblies at runtime from specific subfolders. These assemblies are compiled with dependencies to other assemblies. The runtime trys to load these from the application directory. But I want to put them into the modules directory.
我的应用程序在运行时从特定子文件夹动态加载程序集。这些程序集编译时依赖于其他程序集。运行时尝试从应用程序目录加载这些。但我想把它们放到模块目录中。
Is there a way to tell the runtime that the dlls are in a seperate subfolder?
有没有办法告诉运行时 dll 位于单独的子文件夹中?
采纳答案by Shaun Austin
One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.
我最近使用的一种很好的方法是为 AppDomain 的 AssemblyResolve 事件添加一个事件处理程序。
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
Then in the event handler method you can load the assembly that was attempted to be resolved using one of the Assembly.Load, Assembly.LoadFrom overrides and return it from the method.
然后在事件处理程序方法中,您可以加载尝试使用 Assembly.Load、Assembly.LoadFrom 覆盖之一解析的程序集并从该方法返回它。
EDIT:
编辑:
Based on your additional information I think using the technique above, specifically resolving the references to an assembly yourself is the only real approach that is going to work without restructuring your app. What it gives you is that the location of each and every assembly that the CLR fails to resolve can be determined and loaded by your code at runtime... I've used this in similar situations for both pluggable architectures and for an assembly reference integrity scanning tool.
根据您的其他信息,我认为使用上述技术,特别是自己解决对程序集的引用是唯一可以在不重构您的应用程序的情况下工作的真正方法。它为您提供的是,CLR 无法解析的每个程序集的位置都可以在运行时由您的代码确定和加载......我已经在类似情况下将其用于可插拔架构和程序集引用完整性扫描工具。
回答by samjudson
You can use the <probing>
element in a manifest file to tell the Runtime to look in different directories for its assembly files.
您可以使用<probing>
清单文件中的元素告诉运行时在不同目录中查找其程序集文件。
http://msdn.microsoft.com/en-us/library/823z9h8w.aspx
http://msdn.microsoft.com/en-us/library/823z9h8w.aspx
e.g.:
例如:
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="bin;bin2\subbin;bin3"/>
</assemblyBinding>
</runtime>
</configuration>
回答by jfs
You can use the <codeBase>
element found in the application configuration file. More information on "Locating the Assembly through Codebases or Probing".
您可以使用<codeBase>
在应用程序配置文件中找到的元素。有关“通过代码库或探测定位程序集”的更多信息。
Well, the loaded assembly doesn't have an application configuration file.
好吧,加载的程序集没有应用程序配置文件。
Well if you know the specific folders at runtime you can use Assembly.LoadFrom.
好吧,如果您知道运行时的特定文件夹,您可以使用Assembly.LoadFrom。