Question

I know this could be silly, but would like gurus to clarify it for me... Why is this method defined as static ..

public class MvcApplication : System.Web.HttpApplication
{
    /* Why this method is declared as static? */
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

    }

    protected void Application_Start()
    {
        RegisterRoutes(RouteTable.Routes);
    }
}
Was it helpful?

Solution

its static because it has no need to be a method directly related to instances of the class, but rather a method that can be used in a static context.

In other words, it only affects the parameter "routes", it doesn't use any class fields or members, so it makes sense it be made static.

OTHER TIPS

The method is static because it can be (as Mark points out)... but I think the real reason behind the ASP.NET team making it static (as you're trying to get at with your question of 'why?') was to make unit testing your routes easier.

ASP.NET MVC Pro by Steve Sanderson has a good section (with helper methods) on testing your routes. And I think the MVC Contrib project also has some helper methods for unit testing your routes.

HTHs
Charles

To me it makes sense to have it static so you can get at the routes of (possibly) another application without having to instantiate the app class itself. You can then use these routes to create action URLs, etc, from one application to another.

You only need one routes table and you need the same one used throughout the application. Making it static means you get a global set of values that are defined in a single place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top