Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller not loaded from different assembly?

I'm trying to load a Controller from a different assembly but I'm stuck here.

I have two projects:

  1. Web application
  2. Class library

In the web application I defined a Route:

routes.MapRoute("Root", "root/{Action}", 
                  new {Controller = "Root", Action = "Index" });

Now when I hit the following URL, the route is matched, however a 404 error is thrown. Can anybody tell me why this is happening? (p.s. the RootController is located in the class library)

http://webapp/root

I've tried adding a custom controller factory:

public class ControllerFactory : DefaultControllerFactory {
    protected override IController GetControllerInstance(RequestContext reqContext, Type controllerType)
    {
        // reqContext.Route is correct and has the "Root" route loaded
        // controllerType seems to be null ??

        // if I break execution here and manually set controllerType to
        // typeof(ClassLibrary.RootController) and continue from there,
        // then everything works as expected... 

        // So this method is being called without controllerType... but why??
    }
}

I also tried adding a namespaces property to the route:

routes.MapRoute("Root", "root/{Action}", 
              new {
                Controller = "Root", 
                Action = "Index", 
                Namespaces = new[] { typeof(RootController).Namespace }                     
              });
like image 433
Ropstah Avatar asked Oct 08 '22 07:10

Ropstah


1 Answers

After much debugging and frustration I found that the controller class was declared private which doesn't work in the scenario.

Even though my ControllerFactory is in the same namespace, the classes that create controller caches aren't. Thus the request to GetControllerInstance, which is made by the DefaultControllerFactory base class can't find the RootController class.

Declaring the RootController as public solves the issue.

like image 184
Ropstah Avatar answered Oct 12 '22 20:10

Ropstah