我正在构建一个插件类型的系统,每个插件都表示为一个 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/