gpt4 book ai didi

c# - 是否可以在运行时切换 DLL 以使用不同的版本?

转载 作者:太空狗 更新时间:2023-10-29 23:14:07 28 4
gpt4 key购买 nike

我有一个应用程序,其中包含许多连接到许多不同 I/O 设备的插件 (MEF)。这些插件中的大多数都有许多托管和非托管 dll。

一家制造商最近发布了新固件和新驱动程序。 API 保持不变。

我认为我可以将两个 dll 版本包含在单独的资源文件夹中,并在应用程序启动时将所需的集合复制到输出文件夹中。

(我想我可以制作插件的第二个副本并找出加载正确插件的方法,但我认为复制 DLL 可能更容易 - 特别是考虑到插件代码未更改)

这是行不通的。

static MyClass() // static constructor
{
// required version?
if (envvar.Equals("4") )
{
path = "ver4.1.1";
}
else
{
path = "ver2.5.1";
}

// location of drivers
path = Path.Combine("./Prj/QX", path);
string[] files = Directory.GetFiles(path);

// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
string fileName = Path.GetFileName(s);
string destFile = Path.Combine(".", fileName);
File.Copy(s, destFile, true);
}

// force load of assemby
Assembly assy = LoadWithoutCache("driver.dll");
string fn = assy.FullName;
}

static Assembly LoadWithoutCache(string path)
{
using (var fs = new FileStream(path, FileMode.Open))
{
var rawAssembly = new byte[fs.Length];
fs.Read(rawAssembly, 0, rawAssembly.Length);
return Assembly.Load(rawAssembly);
}
}

错误信息提示原始DLL已加载或应该加载但未能加载。

Could not load file or assembly 'driver, Version=1.5.77, Culture=neutral, PublicKeyToken=983247934' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

有什么方法可以实现我的目标,还是我必须构建我的应用程序的 2 个单独版本?

编辑我还应该说,没有必要同时加载两个 DLL。使用导致加载一个或另一个 DLL 的参数启动应用程序就足够了。

最佳答案

实现此目的的一种(复杂的)方法是:

1。使用 FileSystemWatcher(FSW) 监视文件夹

FSW 检测程序集是否被更改或删除。

2。将程序集加载到 Reflection-Only Context

只能检查加载到此上下文中的程序集!通过获取程序集的类型并检查这些类型是否实现了您的 PluginInterface,确保程序集类型实现了 PluginInterface。

3。使用 Shadow Copying 将程序集加载到单独的 AppDomain 中

由于您只能卸载一个 AppDomain 及其所有程序集,因此您可以在其自己的 AppDomain 中加载每个插件程序集。这样只需卸载插件的 AppDomain。

一定要终止插件的所有进程/线程!

影子复制通过将程序集复制到临时路径来确保原始文件的更改。

4。跟踪加载的程序集

将成功加载的程序集的路径放入列表中。这使得检测程序集是否需要加载/重新加载变得更加容易。

5。处理 FSW 事件

检查更改/删除了哪个 .dll 以卸载程序集,或者是否检测到新程序集以加载它。

6。转到步骤 2


您好,黑长江

关于c# - 是否可以在运行时切换 DLL 以使用不同的版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29938768/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com