12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Threading.Tasks;
- namespace JsonRPC4.Router
- {
- public class RpcEndpointBuilder
- {
- private List<MethodInfo> baseMethods
- {
- get;
- } = new List<MethodInfo>();
- private Dictionary<RpcPath, List<MethodInfo>> methods
- {
- get;
- } = new Dictionary<RpcPath, List<MethodInfo>>();
- public RpcEndpointBuilder AddMethod(RpcPath path, MethodInfo methodInfo)
- {
- Add(path, methodInfo);
- return this;
- }
- public RpcEndpointBuilder AddControllerWithDefaultPath<T>()
- {
- Type typeFromHandle = typeof(T);
- return AddControllerWithDefaultPath(typeFromHandle);
- }
- public RpcEndpointBuilder AddControllerWithDefaultPath(Type controllerType)
- {
- RpcRouteAttribute customAttribute = controllerType.GetCustomAttribute<RpcRouteAttribute>(inherit: true);
- ReadOnlySpan<char> 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<T>(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<MethodInfo> 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<MethodInfo> value;
- if (path == null)
- {
- value = baseMethods;
- }
- else if (!methods.TryGetValue(path, out value))
- {
- List<MethodInfo> list2 = methods[path] = new List<MethodInfo>();
- value = list2;
- }
- value.Add(methodInfo);
- }
- }
- }
|