How to register routes that have been defined outs

2019-09-16 14:07发布

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

2条回答
【Aperson】
2楼-- · 2019-09-16 14:41

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
    }
查看更多
姐就是有狂的资本
3楼-- · 2019-09-16 14:51

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

查看更多
登录 后发表回答