using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using TOOHUCardAPI.Data; using MethodMap = System.Collections.Generic.Dictionary; namespace TOOHUCardAPI.Controllers { public class MethodBasedController : ControllerBase { public delegate Task EndpointHandler(string requestBody); private static Dictionary MethodMapByType; protected Task InvokeEndpointHandlerForMethod(object _this, string method, string body) { MethodMap registeredEndpointHandlers = GetMethodMapForType(); if (registeredEndpointHandlers.ContainsKey(method)) { return ((EndpointHandler) registeredEndpointHandlers[method] .CreateDelegate(typeof(EndpointHandler), _this)).Invoke(body); } throw new MissingEndpointHandlerException(method); } private MethodMap GetMethodMapForType() { if (!MethodMapByType.ContainsKey(typeof(T))) { RegisterEndpointHandlers(); } return MethodMapByType[typeof(T)]; } private static MethodMap RegisterEndpointHandlers() { MethodInfo[] methods = typeof(T).GetMethods(); return methods .Aggregate(new MethodMap(), (handlers, m) => { Attribute attr = m.GetCustomAttribute(typeof(EndpointHandlerAttribute), false); if (attr != null) { EndpointHandlerAttribute e = (EndpointHandlerAttribute) attr; handlers.Add(e.Method, m); } return handlers; }); } } }