具有常见参考的C#负载程序集 [英] C# Load Assembly w/ Common References

查看:118
本文介绍了具有常见参考的C#负载程序集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个小问题-我正在编写一个加载DLL的程序,每个加载的DLL都包含一个类,该类继承自已加载的DLL和宿主程序所引用的库中现有的类。正在加载DLL。这里的问题是,当我尝试加载并强制转换为超类时:

I've run into a slight issue - I'm writing a program that loads DLLs, each of which contain a class which inherits from a class existing in a library referenced by both the loaded DLL and the "host" program that is loading the DLL. The issue here is that, when I try to load and cast to the superclass:

var assembly = Assembly.LoadFrom(dllPath);
var type = assembly.GetTypes().FirstOrDefault(x => x.IsSubclassOf(typeof (MySuperclass)));
...

尽管两者都引用了包含MySuperclass的类,因为dll正在引用内置的类库(与加载程序所引用的类库文件不同的文件)IsSubclassOf永远不会返回true,因为它认为这两个类是不同的,因为它们来自两个不同的程序集。

Although both are referencing the class containing MySuperclass, since the dll is referencing the built class library (a separate file from the class library file the loading program is referencing) IsSubclassOf never returns true, because it considers the two classes to be different as they come from two different assemblies.

此外,如果您尝试将已创建的已加载类的实例强制转换为超类类型,则由于它们不相同(不同的程序集)而无法执行

Furthermore, if you try casting a created instance of the loaded class to the superclass type, it can't do it since they're not the same (different assemblies).

所以,我的问题是:如何处理引用通用代码的程序集,以便c#识别出您正在加载继承自以下类的类:常见的超类?

推荐答案

如果您必须使用相同的汇编文件(即使它们是相同的)希望程序使用通用代码一起工作。这是我解决问题的方法:

You simply must use the same assembly files (even if they are identical) if you want programs to work together using common code. Here's how I solved the issue:

该程序正在从其自己的子目录中加载DLL。

The program is loading a DLL from a subdirectory of its own.

文件夹结构:

MyApp Folder -->
     MyProgram.exe
     CommonDependency.dll
     Submodules ->
         MySubmodule.dll

要让MySubmodule在下一个文件夹中使用CommonDependency.dll,这很简单。将Visual Studio配置为不将这些dll依赖项复制到生成文件夹中。接下来,在Visual Studio中创建一个App.config并添加以下内容:

To get MySubmodule to use CommonDependency.dll within the next folder up, it's quite simple. Configure Visual Studio to not copy these dll dependencies to the build folder. Next, create an App.config in Visual Studio and add the following:

<configuration>
  <runtime>
    <assemblyBinding>
      <probing privatePath="../"/>
    </assemblyBinding>
  </runtime>
</configuration>

这将告诉系统在父文件夹中搜索程序集。 ./-如果要有多个文件夹,也许是单独的依赖项文件夹(相对于.dll的位置),则可以使用; 作为分隔符- ../;../ bin /; -程序将在这些位置中搜索依赖项。

This will tell the system to search for the assemblies in the parent folder ../ - if you want to have multiple folders, perhaps a separate dependency folder (relative to the location of the .dll) you can use ; as the delimiter - ../;../bin/; - the program will search these locations for the dependencies.

这篇关于具有常见参考的C#负载程序集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆