I am trying to create a small web app that will take POST request with code and variables, compile it on the ASP.NET Core server and print result. I did some research and seems like using Roslyn is the only way. After reading guides I came up with the code provided below and found out that after calling GenerateAssembly() method, responsible for creating the assembly and invoking it, .NET Core Host process locks mylib.dll file, until the server is restarted. I tried deleting the file with File.Delete(), but it raised access denied exception. Is there a way to unlock/delete that DLL? One of my ideas was creating DLLs with GUID as name but I think that's not very good solution.
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;
}