using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace JsonRPC4.Router { public class RpcEndpointBuilder { private List baseMethods { get; } = new List(); private Dictionary> methods { get; } = new Dictionary>(); public RpcEndpointBuilder AddMethod(RpcPath path, MethodInfo methodInfo) { Add(path, methodInfo); return this; } public RpcEndpointBuilder AddControllerWithDefaultPath() { Type typeFromHandle = typeof(T); return AddControllerWithDefaultPath(typeFromHandle); } public RpcEndpointBuilder AddControllerWithDefaultPath(Type controllerType) { RpcRouteAttribute customAttribute = controllerType.GetCustomAttribute(inherit: true); ReadOnlySpan path = (customAttribute != null && customAttribute.RouteName != null) ? MemoryExtensions.AsSpan(customAttribute.RouteName) : ((!controllerType.Name.EndsWith("Controller")) ? MemoryExtensions.AsSpan(controllerType.Name) : MemoryExtensions.AsSpan(controllerType.Name, 0, controllerType.Name.IndexOf("Controller"))); RpcPath path2 = RpcPath.Parse(path); return AddController(controllerType, path2); } public RpcEndpointBuilder AddController(RpcPath path = null) { Type typeFromHandle = typeof(T); return AddController(typeFromHandle, path); } public RpcEndpointBuilder AddController(Type type, RpcPath path = null) { foreach (MethodInfo item in Extract(type)) { Add(path, item); } return this; } public IRpcMethodProvider Resolve() { return new StaticRpcMethodProvider(baseMethods, methods); } private IEnumerable Extract(Type controllerType) { return from m in (from t in controllerType.Assembly.GetTypes() where t == controllerType select t).SelectMany((Type t) => t.GetMethods(BindingFlags.Instance | BindingFlags.Public)) where m.DeclaringType != typeof(object) select m; } private void Add(RpcPath path, MethodInfo methodInfo) { List value; if (path == null) { value = baseMethods; } else if (!methods.TryGetValue(path, out value)) { List list2 = methods[path] = new List(); value = list2; } value.Add(methodInfo); } } }