如何卸载由 CSharpCodeProvider 创建的程序集?



>问题

CSharpCodeProvider 可用于将源.cs文件编译到程序集中。 但是,默认情况下,程序集会自动加载到 AppDomain.CurrentDomain 中。就我而言,这是一个问题,因为我需要在运行时能够再次重新编译程序集,并且由于它已经在 CurrentDomain 中加载,因此我无法卸载它,所以我卡住了。

我已经浏览了文档,似乎无法设置目标应用程序域。我也尝试在谷歌上搜索它,只找到了使用Assembly.Load的答案,我认为我不能使用它,因为我需要从原始源代码编译,而不是.dll

一个人该怎么做呢?是否有任何替代方案或解决方法?

主程序

using (var provider = new CSharpCodeProvider())
{
  param.OutputAssembly = "myCompiledMod"
  var classFileNames = new DirectoryInfo("C:/sourceCode").GetFiles("*.cs", SearchOption.AllDirectories).Select(fi => fi.FullName).ToArray();
  CompilerResults result = provider.CompileAssemblyFromFile(param, classFileNames);
  Assembly newAssembly = result.CompiledAssembly // The assembly is already in AppDomain.CurrentDomain!
  // If you try compile again, you'll get an error; that class Test already exists
}

C:/sourceCode/test.cs

public class Test {}


我已经尝试过了

我已经尝试创建一个新的应用程序域并将其加载到其中。发生的情况是程序集最终被加载到两个域中。

// <snip>compile code</snip>
Evidence ev = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain("NewDomain", ev);
domain.Load(newAssembly);

答案是使用 CSharpCodeProvider((。CreateCompiler(( 而不仅仅是 CSharpCodeProvider,并设置 param。生成内存为假。现在我能够看到行号,并且没有正在创建可见的程序集.dll文件,尤其是没有被锁定。这允许将程序集保留在内存中并在需要时重新加载它。

最新更新