我可以动态创建一个类,然后实例化它并从 Visual Studio 的即时窗口调用其中的一个方法。但是我不能使 MVC 控制器类的行为像预期的那样(即被找到并路由到)。我错过了什么?
全球.asax.cs:
protected void Application_Start()
{
RoslynExperiments.AddController();
RegisterRoutes(RouteTable.Routes);
...
罗斯林实验:
public static void AddController()
{
var controllerCode = @"using System.Web.Mvc;
public class FooController:Controller
{
public ActionResult Index()
{
return Content(""foo"");
}
}
";
AddDynamicAssemblyClass("FooController", controllerCode);
}
public static void AddDynamicAssemblyClass(string inMemoryAssemblyName, string code)
{
var syntaxTree = SyntaxTree.ParseText(code);
var refs = new[] {
MetadataReference.CreateAssemblyReference("mscorlib"),
MetadataReference.CreateAssemblyReference("System"),
MetadataReference.CreateAssemblyReference("System.Web"),
MetadataReference.CreateAssemblyReference("System.Web.MVC")
};
var compilation = Compilation.Create(inMemoryAssemblyName,
syntaxTrees: new[] { syntaxTree },
references: refs,
options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (var memoryStream = new MemoryStream())
{
EmitResult result = compilation.Emit(memoryStream);
memoryStream.Flush();
var assembly = Assembly.Load(memoryStream.GetBuffer());
}
}