I can create a class dynamically, and then instantiate it and call a method within it from the immediate window in Visual Studio. But I cannot make a MVC Controller class behave like expected (i.e. be found and routed to). What am I missing?
Global.asax.cs:
protected void Application_Start()
{
RoslynExperiments.AddController();
RegisterRoutes(RouteTable.Routes);
…
RoslynExperiments:
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());
}
}
I don’t have much experience with ASP.NET MVC rounting, but according to one comment, only controllers from referenced assemblies are considered, not from all loaded assemblies.
Because of that, I think you need to use a custom
ControllerFactory.