c# - 在使用时换出 DLL

标签 c# dll

我正在构建一个插件类型的系统,每个插件都表示为一个 DLL。我希望能够在不停止主应用程序的情况下重新加载它们。这意味着它们必须在运行时加载,它们之间没有预先构建的链接(对 dll 进行文件搜索并加载它们)。我使用 Assembly.LoadFile(filename) 进行了设置,但是,当我尝试使用 File.Copy 替换 DLL 时,它会抛出异常,类似于'正在使用的文件'。我试过使用 AppDomain,通过这个辅助域加载所有插件,并在重新加载之前卸载它,但这会引发相同的异常。

我当前的代码:

        if (pluginAppDomain != null)
            AppDomain.Unload(pluginAppDomain);
        foreach (string s in Directory.GetFiles(path_to_new_DLLs))
        {
            string name = s.Substring(s.LastIndexOf('\\') + 1);
            Console.WriteLine("Copying " + name);
            File.Copy(s, Path.Combine(current_directory, name), true); // Throws exception here
        }
        AppDomainSetup setup = new AppDomainSetup();
        setup.ApplicationBase = Environment.CurrentDirectory;
        setup.ShadowCopyFiles = "true"; 
        // I think this is where the problem is, maybe I'm forgetting to set something
        pluginAppDomain = AppDomain.CreateDomain("KhybotPlugin", null, setup);
        foreach (String s in Directory.GetFiles(Environment.CurrentDirectory, "*.dll"))
        {
            int pos = s.LastIndexOf('\\') + 1;
            Assembly dll = pluginAppDomain.Load(s.Substring(pos, s.Length - pos - 4));
            // Elided... Load types from DLL, etc, etc
        }

最佳答案

通常您需要卸载 AppDomain 才能进行通信。 如果您想防止上述错误,您只需使用 Assembly.Load(Byte[]) 加载您的 dll。

您还可以使用 Managed Extensibility Framework这将为您节省大量工作。

Assembly.Load问题解决方案

Assembly loaded using Assembly.LoadFrom() on remote machine causes SecurityException

关于c# - 在使用时换出 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9980107/

相关文章:

c# - 数据透视表中的 OpenOfficeXml 重复标签

c# - Azure DevOps YAML 管道失败并显示 "A sequence was not expected"

c# - return false 必须停止 JavaScript 中的执行

c# - 我可以从 64 位应用程序以 32 位运行 C# 程序集 (dll) 吗?

c# - 模块化 C# Winform 应用程序

winapi - LoadLibrary 失败并且依赖遍历器没有帮助

c++ - 在 dll 接口(interface)中使用 shared_ptr

c# - C#/SQL Server 2016-更新大约1亿条具有哈希值的记录

c# - DotNetOpenAuth 和谷歌

c# - 在 C# 中从 Go 调用函数