装载程序集及其依赖程序

2023-09-02 01:46:53 作者:人潮拥挤我需要你

我的应用程序动态加载组件从具体的​​子文件夹中运行。这些组件与依赖于其他程序集编译。运行时改掉从应用程序目录加载这些。但我想将它们放入modules目录。

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.

有没有办法告诉大家,这些DLL在一个单独的子文件夹中运行?

Is there a way to tell the runtime that the dlls are in a seperate subfolder?

推荐答案

一个不错的方法我最近使用的是添加一个事件处理程序的AppDomain的AssemblyResolve事件。

One nice approach I've used lately is to add an event handler for the AppDomain's AssemblyResolve event.

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

然后在事件处理程序方法,你可以加载在试图使用一个的Assembly.Load,Assembly.LoadFrom覆盖,并从该方法返回解决的组装。

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.

编辑:

根据您的其他信息我认为使用上述技术,专门解决引用装配自己是去没有调整您的应用程序工作的唯一真正的方法。什么它给你的每一个位置,而且CLR未能解决,可确定和你的code运行时加载的每一个组件......我为可插拔架构和一个用这种类似的情况集引用完整性扫描工具。

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.