ASP.NET MVC: Get all controllers

后端 未结 2 959
孤城傲影
孤城傲影 2020-12-08 05:26

Is it possible to get all controllers available to a ControllerFactory?
What I want to do is get a list of all controller types in application, but in a consistent way.<

2条回答
  •  再見小時候
    2020-12-08 06:16

    I don't think it's possible to give a simple answer to this question, because it depends on a lot of different things, including the implementation of IControllerFactory.

    For instance, if you have a completely custom-built IControllerFactory implementation, all bets are off, because it may use any sort of mechanism to create Controller instances.

    However, the DefaultControllerFactory looks after the appropriate Controller type in all the assemblies defined in the RouteCollection (configured in global.asax).

    In this case, you could loop through all the assemblies associated with the RouteCollection, and look for Controllers in each.

    Finding Controllers in a given assembly is relatively easy:

    var controllerTypes = from t in asm.GetExportedTypes()
                          where typeof(IController).IsAssignableFrom(t)
                          select t;
    

    where asm is an Assembly instance.

提交回复
热议问题