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
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: /Views/TestModuleApi/Index.cshtml /Views/Shared/Index.cshtml.
I also tried a very simple approach to
return whatever I want:
actionContext.RouteData.Values["controller"] = "MyApi"; actionContext.RouteData.Values["action"] = "Get"; return new MyApiController();
Here I am overriding each call
to return an instance
. In this case,
. However, when I go to
, for example, I get the values from
How is it possible in a custom implementation
to instantiate the controller we need?
UPDATE: When I debug the first code, I see that the constructor is called
, but the action is
source to share
No one has answered this question yet
See similar questions: