题
是否有可能获得的所有控制器可用于ControllerFactory?
什么我要做的就是一个列表中的所有控制器类型中的应用程序,但在一个一致的方式。
因此,所有控制我得到的是默认的请求的决议是使用。
(实际的任务是找到所有行动的方法,有一定属性)。
解决方案
你可以使用反映列举的所有类在一个组件,以及过滤器的唯一类继承从控制器类。
最好的参考 asp.net 视的源代码.看一看的实现 ControllerTypeCache 和 ActionMethodSelector 类。ControllerTypeCache显示如何获取所有控制器类。
internal static bool IsControllerType(Type t) {
return
t != null &&
t.IsPublic &&
t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) &&
!t.IsAbstract &&
typeof(IController).IsAssignableFrom(t);
}
public void EnsureInitialized(IBuildManager buildManager) {
if (_cache == null) {
lock (_lockObj) {
if (_cache == null) {
List<Type> controllerTypes = GetAllControllerTypes(buildManager);
var groupedByName = controllerTypes.GroupBy(
t => t.Name.Substring(0, t.Name.Length - "Controller".Length),
StringComparer.OrdinalIgnoreCase);
_cache = groupedByName.ToDictionary(
g => g.Key,
g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase),
StringComparer.OrdinalIgnoreCase);
}
}
}
}
和ActionMethodSelector显示如何检查,如果一方法有所需的属性。
private static List<MethodInfo> RunSelectionFilters(ControllerContext controllerContext, List<MethodInfo> methodInfos) {
// remove all methods which are opting out of this request
// to opt out, at least one attribute defined on the method must return false
List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();
List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();
foreach (MethodInfo methodInfo in methodInfos) {
ActionMethodSelectorAttribute[] attrs = (ActionMethodSelectorAttribute[])methodInfo.GetCustomAttributes(typeof(ActionMethodSelectorAttribute), true /* inherit */);
if (attrs.Length == 0) {
matchesWithoutSelectionAttributes.Add(methodInfo);
}
else if (attrs.All(attr => attr.IsValidForRequest(controllerContext, methodInfo))) {
matchesWithSelectionAttributes.Add(methodInfo);
}
}
// if a matching action method had a selection attribute, consider it more specific than a matching action method
// without a selection attribute
return (matchesWithSelectionAttributes.Count > 0) ? matchesWithSelectionAttributes : matchesWithoutSelectionAttributes;
}
其他提示
我不认为这是可以给出一个简单的回答这个问题,因为它取决于很多不同的东西,包括IControllerFactory的实现。
举例来说,如果你有一个完全定制IControllerFactory实施,全盘皆输,因为它可以使用的任何的排序机制的创建Controller实例。
然而,DefaultControllerFactory在RouteCollection定义的所有组件适当的控制器类型(在global.asax中配置)后的外观。
在此情况下,可以通过所有与RouteCollection相关联,并且在每个查找控制器。该组件循环
查找控制器在给定组件相对容易:
var controllerTypes = from t in asm.GetExportedTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
其中asm
是装配实例。
不隶属于 StackOverflow