ControllerPublicMethodProvider.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using EdjCase.JsonRpc.Router.Abstractions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Reflection;
  8. namespace EdjCase.JsonRpc.Router.MethodProviders
  9. {
  10. /// <summary>
  11. /// Method provider finding all public methods through reflection
  12. /// </summary>
  13. public class ControllerPublicMethodProvider : IRpcMethodProvider
  14. {
  15. /// <summary>
  16. /// List of types to match against
  17. /// </summary>
  18. public IReadOnlyList<Type> Types { get; }
  19. private List<MethodInfo> methodCache { get; set; }
  20. /// <param name="types">List of types to match against</param>
  21. public ControllerPublicMethodProvider(List<Type> types)
  22. {
  23. if (types == null || !types.Any())
  24. {
  25. throw new ArgumentException("At least one type must be specified.", nameof(types));
  26. }
  27. this.Types = types;
  28. }
  29. /// <param name="type">Type to match against</param>
  30. public ControllerPublicMethodProvider(Type type)
  31. {
  32. if (type == null)
  33. {
  34. throw new ArgumentNullException(nameof(type));
  35. }
  36. this.Types = new List<Type> { type };
  37. }
  38. public List<MethodInfo> GetRouteMethods()
  39. {
  40. if (this.methodCache == null)
  41. {
  42. var methods = new List<MethodInfo>();
  43. foreach (Type type in this.Types)
  44. {
  45. List<MethodInfo> publicMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  46. //Ignore ToString, GetHashCode and Equals
  47. .Where(m => m.DeclaringType != typeof(object))
  48. .ToList();
  49. methods.AddRange(publicMethods);
  50. }
  51. this.methodCache = methods;
  52. }
  53. return this.methodCache;
  54. }
  55. }
  56. }