4

This is a point of curiosity rather than an actual problem I'm having: how does the ASP.NET MVC framework create the appropriate controller and view objects from the string name in the RouteCollection? I've tried searching through the actual ASP.NET MVC2 code to figure this out but get lost in the controller factory class.

When I register my routes, I map the first block to the controller, the second to an action, the third to an ID, but how does the program take string names and create new objects?

/Users/Update/15354 = New UserController, executes Update() - how?

The only thing I can imagine working is reflecting through all the classes in the project and creating one that matches the requested name, but then how would you resolve a conflict in class names without knowing which namespace to use?

2
  • ASP.NET MVC throws an exception if there is a name collision. Commented Mar 1, 2011 at 20:36
  • @Omar It's not quite that simple. An exception will only be thrown if there is a name collision and the routes which are defined in the application are missing an explicit namespace. Commented Mar 1, 2011 at 20:40

1 Answer 1

4

The standard naming convention "FooController" dictates that all controllers should have the suffix "Controller"; thus, when your current route indicates the controller "Foo", ASP.NET MVC examines the types within your application which inherit from Controller and looks for one whose name matches "Foo" + "Controller".

You are correct to assume that ASP.NET MVC is using reflection to find the desired controller, but it is a relatively low impact because the reflection data is cached by the application during its initial startup.

If you have two controllers with the same name and different namespaces, you can use the alternative form of MapRoute() to indicate which controller you intend to resolve.

routes.MapRoute(
    "Error_ServiceUnavailable",
    "error/service-unavailable",
    new { controller = "Error", action = "ServiceUnavailable" },
    new[] { "Controllers" }
);

routes.MapRoute(
    "Admin_Error_ServiceUnavailable",
    "admin/error/service-unavailable",
    new { controller = "Error", action = "ServiceUnavailable" },
    new[] { "Areas.Admin.Controllers" }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.