How to register routes that have been defined outside Global.asax

半城伤御伤魂 提交于 2019-12-12 05:31:55

问题


I'm trying to implement the pattern that's introduced by this question

The accepted answer provides a strategy where routes have been defined in a separate class. The question I have is exactly how to call that code from Global.asax.

thx


回答1:


See another answer from the same question, or more specifically the link provided in that answer.

All that you should have to do is add an instance of ExampleRoute to the RouteCollection in the global.asax.

    public static void RegisterRoutes(RouteCollection routes)
    {
        // ...other routes
        routes.Add(new ExampleRoute());
        // ...more routes
    }



回答2:


Let me show you how can you register route which is specified anywhere in the project as long as the dll file containing lies in the bin folder.

define an interface

public interface IRegiserRoute
{
    void RegisterRoutes(RouteCollection routes);
}

Now say you want to register some route some where far in the jungle. Create a class and inherit it from the above given interface.

public MyBlogRoutes : IRegiserRoute
{
    public void RegisterRoutes(RouteCollection routes)
    {
        //register your stuff here. 

    }

}

Now how to call this route from global.asax file. Load all the types which are inherited from IRegiserRoute (from How to find all the classes which implement a given interface?)

var type = typeof(IRegiserRoute);
var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
.SelectMany(a => a.GetTypes())
.Where(t => type.IsAssignableFrom(t))
select Activator.CreateInstance(t) as IRegiserRoute;

//Now register all your routes anywhere in bin folder.

foreach (var t in types)
{
  t.RegisterRoutes(routes); 
}

I hope this should get you going.

cheers

Parminder



来源:https://stackoverflow.com/questions/8733181/how-to-register-routes-that-have-been-defined-outside-global-asax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!