11

我到处看到的 MVC 风格路由的例子是这样的:

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    routes.Add(new Route
    (
         "Category/{action}/{categoryName}"
         , new CategoryRouteHandler()
    ));
}

将 RouteTable.Routes 集合传递给 RegisterRoutes() 的原因是什么?为什么不只是:

void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes();
}

public static void RegisterRoutes()
{
    RouteTable.Routes.Add(new Route
    (
         "Category/{action}/{categoryName}"
         , new CategoryRouteHandler()
    ));
}

除了 RouteTable.Routes 之外,还有哪些 RouteCollection 会添加路由?RouteTable.Routes 不是Web 应用程序RouteCollection 吗?

我有一个具有 Map() 方法的特定 IRouteHandler:

public class ChatRouteHandler : IRouteHandler
{
    private static bool mapped;

    public void Map()
    {
        if (!ChatRouteHandler.mapped)
        {
            RouteTable.Routes.Add
            (
                new Route("chat/{room}/{date}", 
                new ChatRouteHandler())
            );
        }
    }

Map() 是否有理由接受 RouteCollection 而不是添加到 RouteTable.Routes 集合中?同样,这个 IRouteHandler 还会添加到其他哪些 RouteCollection 中?

4

1 回答 1

13

单元测试。

通过从 RouteTable.Routes 中解耦(通过参数传递)注册,您可以选择在单元测试中使用哪个 RouteCollection 进行注册。

IMHO, it's also nicer to write routes.Add() instead of RouteTable.Routes.Add() everywhere.

"Is there a reason that Map() should accept a RouteCollection and not add to the RouteTable.Routes collection?"

I'm interpreting this question as "Why doesn't RouteCollection have the MapRoute method, instead of an extension method?". Yeah, RouteCollection is in System.WEb.Routing, whilst MapRoute extension method is in System.Web.Mvc. MapRoute() depends on MvcHandler, which System.Web.Routing has no idea about.

于 2009-03-30T04:37:43.973 回答