在MVC 3应用程序内运行时编译(dll生成)

Dry*_*ods 6 asp.net asp.net-mvc-3

为了测试,我使用了具有以下源代码的Console应用程序:

    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);
    }
Run Code Online (Sandbox Code Playgroud)

使用此代码在控制台应用程序中,我可以使其工作并创建AutoGen.dll文件,从那时我可以调用计算器的方法.

当我在MVC 3应用程序中执行相同的代码时,我的问题就出现了.如果我使用以下变量,我可以捕获异常.

var compileResult1 = provider.CompileAssemblyFromSource(cp, CODEInString);
Run Code Online (Sandbox Code Playgroud)

'compileResult1.CompiledAssembly'引发System.IO.FileNotFoundException类型的异常'

我还尝试使用Server.MapPath("〜/ bin /")来告诉输出目录.

有人可以帮我吗?谢谢

更新1 我给了正确的用户文件夹的权限,以便写,所以这不是问题.

Dar*_*rov 0

我还尝试使用 Server.MapPath("~/bin/") 来告诉输出目录。

你究竟是如何尝试的,因为以下内容对我有用:

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

这是我的完整测试代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

只是想指出,在执行此操作之前,我希望您充分意识到,通过写入该bin文件夹,您每次运行此代码时基本上都会杀死并卸载 Web 应用程序的 AppDomain。因此,如果您确实想执行一些动态代码,您可以考虑在内存中编译程序集。