How to register routes that have been defined outs

2019-09-16 14:05发布

问题:

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