我正在尝试创建一个小型 Web 应用程序,它将使用代码和变量接收 POST 请求,在 ASP.NET Core 服务器上编译它并打印结果。我做了一些研究,似乎使用 Roslyn 是唯一的方法。在阅读指南后,我想出了下面提供的代码,发现在调用 GenerateAssembly() 方法后,负责创建程序集并调用它,.NET Core Host 进程锁定 mylib.dll 文件,直到服务器重新启动。我尝试使用 File.Delete() 删除文件,但它引发了拒绝访问异常。有没有办法解锁/删除那个 DLL?我的想法之一是创建以 GUID 为名称的 DLL,但我认为这不是一个很好的解决方案。
public static object GenerateAssembly(string code, string[] param)
{
var tree = SyntaxFactory.ParseSyntaxTree(code);
string fileName = "mylib.dll"; //Guid.NewGuid().ToString() + ".dll";
// Detect the file location for the library that defines the
// object type
var systemRefLocation = typeof(object).GetTypeInfo().Assembly.Location;
// Create a reference to the library
var systemReference = MetadataReference.CreateFromFile(systemRefLocation);
var compilation = CSharpCompilation.Create(fileName)
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
.AddReferences(systemReference)
.AddSyntaxTrees(tree);
path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
var compilationResult = compilation.Emit(path); // On 2nd call exception is raised on this line
Assembly asm = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);
object result = asm.GetType("RoslynCore.Helper").GetMethod("Calculate").
Invoke(null, new object[] { param });
return result;
}
相关分类