Compile at runtime (dll generation) inside an MVC 3 application

For testing, I used a console application with the following source code:

public string CODEInString = @"namespace MyNamespace.Generator { public class Calculator { public int Sum(int a, int b) { return a + b; } } }"; public void Create() { var provider = new CSharpCodeProvider(); var cp = new CompilerParameters { GenerateInMemory = false, OutputAssembly = "AutoGen.dll" }; provider.CompileAssemblyFromSource(cp, CODEInString); } 

Using this code inside the console application, I can make it work, and the AutoGen.dll file will be created, from this point I can request calculator methods.

My problem occurs when I do the same code, but inside an MVC 3 application. I can catch an exception if I use the following variable.

 var compileResult1 = provider.CompileAssemblyFromSource(cp, CODEInString); 

'compileResult1.CompiledAssembly' threw an exception of type System.IO.FileNotFoundException '

I also tried using Server.MapPath ("~ / bin /") to tell the output directory.

Can anybody help me? Thanks you

UPDATE 1 I gave permissions to the correct user for recording, so this is not a problem.

+6
source share
1 answer

I also tried using Server.MapPath ("~ / bin /") to specify the output directory.

How exactly did you try this because the following works for me:

 var cp = new CompilerParameters { GenerateInMemory = false, OutputAssembly = Server.MapPath("~/bin/AutoGen.dll") }; 

And here is my full test code:

 public ActionResult Index() { var code = @" namespace MyNamespace.Generator { public class Calculator { public int Sum(int a, int b) { return a + b; } } } "; var provider = new CSharpCodeProvider(); var cp = new CompilerParameters { GenerateInMemory = false, OutputAssembly = Server.MapPath("~/bin/AutoGen.dll") }; var cr = provider.CompileAssemblyFromSource(cp, code); var calcType = cr.CompiledAssembly.GetType("MyNamespace.Generator.Calculator"); var calc = Activator.CreateInstance(calcType); var result = (int)calcType.InvokeMember("Sum", BindingFlags.InvokeMethod, null, calc, new object[] { 1, 2 }); return Content("the result is " + result); } 

I just want to note that before that, I hope that you are fully aware that by writing to the bin folder, you basically kill and unload the AppDomain of your web application every time you run this code. Therefore, if you really want to execute some kind of dynamic code, you might consider compiling the assembly in memory.

0
source

Source: https://habr.com/ru/post/906545/


All Articles