static RestHandler() { Type t = typeof(IHandlerServices); Type ctxType = typeof(HttpContext); _handler = t.Assembly.GetTypes().Where(type => !type.IsInterface && !type.IsAbstract && t.IsAssignableFrom(type)).ToDictionary(type => Regex.Replace(type.Name, "(\\w+)Handler", "$1").ToLower(), type => { var container = new HandlerContainer { Handler = Activator.CreateInstance(type), Methods = new Dictionary<string, HandlerMethodInfo>() }; foreach (var method in type.GetMethods(System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)) { var name = method.Name.ToLower(); if (!container.Methods.ContainsKey(name)) { var args = method.GetParameters(); var mi = new HandlerMethodInfo { ResultType = ServicesResult.GetResultType(method.ReturnType), ArgCount = args.Length, IsHttpContextArg = args.Length == 1 && args[0].ParameterType.Equals(ctxType), Method = method }; container.Methods.Add(name, mi); } } return container; }); }
internal void _handleInternal(IDispatchable eventToHandle) { HandlerMethodInfo handlerMethodInfo = null; _handlerMethods.TryGetValue(eventToHandle.GetType(), out handlerMethodInfo); if (handlerMethodInfo != null && eventToHandle != null) { handlerMethodInfo.Method.Invoke(handlerMethodInfo.Target, new object[] { eventToHandle }); } }
/// <summary> /// Register individual IDispatchable type handler methods. /// NOTE: We could use reflection to populate the _handlerMethods dict at startup automatically, /// but I'm not sure that the potential ambiguity outweighs having to type _registerTypeHandler /// </summary> /// <param name="handlerAction">Handler method to register. Will be called when objects are sent.</param> protected void _registerTypeHandler <T>(Action <T> handlerAction) { Type typeToRegister = typeof(T); HandlerMethodInfo handlerMethodInfo = null; if (_handlerMethods.TryGetValue(typeToRegister, out handlerMethodInfo)) { // already registered, update method handlerMethodInfo.Target = handlerAction.Target; handlerMethodInfo.Method = handlerAction.Method; return; } handlerMethodInfo = new HandlerMethodInfo(); handlerMethodInfo.Target = handlerAction.Target; handlerMethodInfo.Method = handlerAction.Method; _handlerMethods.Add(typeToRegister, handlerMethodInfo); }