Manually create controllers in MVC 6 with custom IControllerFactory implementation

Based on this post, I created a custom factory controller to instantiate controllers based on some logic (to create a pluggable architecture).

For testing purposes, everything looks tough.

var controller = Bootstrapper.GetInstance<Controller>("TestModuleApi");

actionContext.RouteData.Values["controller"] = "TestModuleApi";
actionContext.RouteData.Values["action"] = "Get";
var returnController = _controllerActivator.Create(actionContext, controller.GetType());

return returnController;



gets a controller instance with MEF from the exported controllers folder.

When I open the default Home / Index route, the code goes through here and the variable returnController

is an instance of the required controller. Even if I get the error

An unhandled exception occurred while processing the request.

InvalidOperationException: The view 'Index' was not found. The following locations were searched:


I also tried a very simple approach to CreateController

return whatever I want:

actionContext.RouteData.Values["controller"] = "MyApi";
actionContext.RouteData.Values["action"] = "Get";

return new MyApiController();


Here I am overriding each call CreateController

to return an instance MyApiController

. In this case, MyApiController

inherits HomeApiController

. However, when I go to /api/HomeApi/Get

, for example, I get the values ​​from HomeApiController

, not MyApiController


How is it possible in a custom implementation IControllerFactory

to instantiate the controller we need?

UPDATE: When I debug the first code, I see that the constructor is called TestModuleApiController

, but the action is Get

never called.


source to share

All Articles