RpcEndpointBuilder.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. namespace JsonRPC4.Router
  7. {
  8. public class RpcEndpointBuilder
  9. {
  10. private List<MethodInfo> baseMethods
  11. {
  12. get;
  13. } = new List<MethodInfo>();
  14. private Dictionary<RpcPath, List<MethodInfo>> methods
  15. {
  16. get;
  17. } = new Dictionary<RpcPath, List<MethodInfo>>();
  18. public RpcEndpointBuilder AddMethod(RpcPath path, MethodInfo methodInfo)
  19. {
  20. Add(path, methodInfo);
  21. return this;
  22. }
  23. public RpcEndpointBuilder AddControllerWithDefaultPath<T>()
  24. {
  25. Type typeFromHandle = typeof(T);
  26. return AddControllerWithDefaultPath(typeFromHandle);
  27. }
  28. public RpcEndpointBuilder AddControllerWithDefaultPath(Type controllerType)
  29. {
  30. RpcRouteAttribute customAttribute = controllerType.GetCustomAttribute<RpcRouteAttribute>(inherit: true);
  31. 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")));
  32. RpcPath path2 = RpcPath.Parse(path);
  33. return AddController(controllerType, path2);
  34. }
  35. public RpcEndpointBuilder AddController<T>(RpcPath path = null)
  36. {
  37. Type typeFromHandle = typeof(T);
  38. return AddController(typeFromHandle, path);
  39. }
  40. public RpcEndpointBuilder AddController(Type type, RpcPath path = null)
  41. {
  42. foreach (MethodInfo item in Extract(type))
  43. {
  44. Add(path, item);
  45. }
  46. return this;
  47. }
  48. public IRpcMethodProvider Resolve()
  49. {
  50. return new StaticRpcMethodProvider(baseMethods, methods);
  51. }
  52. private IEnumerable<MethodInfo> Extract(Type controllerType)
  53. {
  54. return from m in (from t in controllerType.Assembly.GetTypes()
  55. where t == controllerType
  56. select t).SelectMany((Type t) => t.GetMethods(BindingFlags.Instance | BindingFlags.Public))
  57. where m.DeclaringType != typeof(object)
  58. select m;
  59. }
  60. private void Add(RpcPath path, MethodInfo methodInfo)
  61. {
  62. List<MethodInfo> value;
  63. if (path == null)
  64. {
  65. value = baseMethods;
  66. }
  67. else if (!methods.TryGetValue(path, out value))
  68. {
  69. List<MethodInfo> list2 = methods[path] = new List<MethodInfo>();
  70. value = list2;
  71. }
  72. value.Add(methodInfo);
  73. }
  74. }
  75. }