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
2010-06-02 13:38:52
Thanks for your resonse, but a Question the Array of Strings get filled manually or automatically in your configuration?Thanks in advance Johannes
john84
2010-06-02 18:49:15
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
2010-06-02 20:41:51
Ok cool, Thanks
john84
2010-06-03 06:46:01
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
2010-06-02 23:11:39
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
2010-06-03 06:48:58