tags:

views:

50

answers:

2

Can I configure MVC to directly look into a class library ("MyApp.Controllers" for example) instead of the foder Controllers?

+2  A: 

Yes, you can. The easiest way is to add the namespace of your class library to the routers.MapRoute call in global.asax. This is how one of our configurations look like:

public static void RegisterRoutes(RouteCollection routes, IEnumerable<string> controllerNamespaces)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
    routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

    routes.MapRoute(
        "Default",                                              // Route name
        "{controller}/{action}/{id}",                           // URL with parameters
        new { controller = "Home", action = "Index", id = "" },  // Parameter defaults
        controllerNamespaces.ToArray()
        );
}

Notice that we use an overload of MapRoute that allows us to supply a string array of controller namespaces.

Another option is to implement a custom IControllerFactory, but that's more work and usually not necessary.

Mark Seemann
Thanks for your resonse, but a Question the Array of Strings get filled manually or automatically in your configuration?Thanks in advance Johannes
john84
Semi-manually in our case. We scan a list of assemblies for IController implementations and project that into a distinct list of namespaces, but you could also do it manually.
Mark Seemann
Ok cool, Thanks
john84
A: 

The ASP.NET MVC runtime knows nothing about a folder named 'Controllers', that is just a project structure convention. You can have your controllers on any assembly, on any namespace, and it should work without any special configuration.

Max Toro
Well, I Agree with Models, there is no problem because I specify the Namespace inside of my Controller, which can be simply changed from the Models Folder to a Models Class Library. But in case of the Controllers it does not seem as I can change the Namespace...right?
john84
@Johannes: All I can say is try it yourself if you don't believe me.
Max Toro