ReflectionHelper.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection;
  6. using Microsoft.Extensions.DependencyInjection;
  7. namespace Bowin.Common.Utility
  8. {
  9. public static class ReflectionHelper
  10. {
  11. private static Assembly ServiceAssembly { get; set; }
  12. private static Assembly IServiceAssembly { get; set; }
  13. public static void AddServiceAssembly(this IServiceCollection service, Assembly serviceAssembly, Assembly interfaceAssembly)
  14. {
  15. ServiceAssembly = serviceAssembly;
  16. IServiceAssembly = interfaceAssembly;
  17. }
  18. public static object CreateByFullName(string classFullName)
  19. {
  20. try
  21. {
  22. string[] classNames = classFullName.Split(',');
  23. return Assembly.Load(classNames[1]).CreateInstance(classNames[0]);
  24. }
  25. catch
  26. {
  27. return null;
  28. }
  29. }
  30. public static object RunMethod(string methodFullName, params object[] methodParameters)
  31. {
  32. IList<string> names = methodFullName.Split('.').ToList();
  33. if (names.Count <= 2)
  34. {
  35. throw (new Exception("方法名输入错误。"));
  36. }
  37. string methodName = names.Last();
  38. names.RemoveAt(names.Count - 1);
  39. string className = string.Join(".", names);
  40. string classShortName = names.Last();
  41. var classType = ServiceAssembly.GetType(className);
  42. if (classType == null)
  43. {
  44. classType = IServiceAssembly.GetType(className);
  45. }
  46. Type myInterface;
  47. if (classType.IsInterface)
  48. {
  49. myInterface = classType;
  50. }
  51. else
  52. {
  53. myInterface = classType.GetInterfaces().Where(x => x.Name == "I" + classShortName).FirstOrDefault();
  54. }
  55. var myClass = HttpHelper.GetService(myInterface);
  56. var myMethod = myClass.GetType().GetMethod(methodName);
  57. try
  58. {
  59. return myMethod.Invoke(myClass, methodParameters);
  60. }
  61. catch (Exception ex)
  62. {
  63. throw (new Exception(ex.InnerException.Message));
  64. }
  65. }
  66. }
  67. }