Jan 15, 2010

Namespace and Controller in asp.net mvc

In .net a type has a namespace, if two type names are the same, but they live in different namespace, this is not a problem. So when asp.net resolve the type with the controller name, DefaultController factory by default does not care namespace. So if there are two Controllers with the sname name in your reference dlls, then there will be an exception saying ambigous controllers found. But you can help the DefaultControllerFactory to resolve this conflict using the follow sample code.

string[] routeContollerSearchHints_NameSpace = new string[] { "MvcAppTest.Controllers" };
string routeName = "Default";
string url = "{controller}/{action}/{id}";
object defaults = new { controller = "Home", action = "Index", id = "" };
object constrants = null;
routes.MapRoute(routeName, url, defaults, constrants, routeContollerSearchHints_NameSpace);

// or 
string[] globalContollerSearchHints_NameSpace = new string[] { "MvcAppTest.Controllers" };
ControllerBuilder.Current.DefaultNamespaces.UnionWith(globalContollerSearchHints_NameSpace);