ReflectorHelper.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Autofac;
  6. using System.Reflection;
  7. namespace EMIS.Utility
  8. {
  9. public class ReflectorHelper
  10. {
  11. /// <summary>
  12. /// Services方法
  13. /// </summary>
  14. /// <param name="methodFullName"></param>
  15. /// <param name="methodParameters"></param>
  16. /// <returns></returns>
  17. public static object RunMethod(string methodFullName, params object[] methodParameters)
  18. {
  19. IList<string> names = methodFullName.Split('.').ToList();
  20. if (names.Count <= 2)
  21. {
  22. throw (new Exception("方法名输入错误。"));
  23. }
  24. string methodName = names.Last();
  25. names.RemoveAt(names.Count - 1);
  26. string className = string.Join(".", names);
  27. string classShortName = names.Last();
  28. var classType = Assembly.Load("EMIS.CommonLogic").GetType(className);
  29. if (classType == null)
  30. {
  31. classType = Assembly.Load("EMIS.ICommonLogic").GetType(className);
  32. }
  33. Type myInterface;
  34. if (classType.IsInterface)
  35. {
  36. myInterface = classType;
  37. }
  38. else
  39. {
  40. myInterface = classType.GetInterfaces().Where(x => x.Name == "I" + classShortName).FirstOrDefault();
  41. }
  42. using (var container = AutofacHelper.Container.BeginLifetimeScope())
  43. {
  44. var myClass = container.Resolve(myInterface);
  45. var myMethod = myClass.GetType().GetMethod(methodName);
  46. try
  47. {
  48. return myMethod.Invoke(myClass, methodParameters);
  49. }
  50. catch (Exception ex)
  51. {
  52. throw (new Exception(ex.InnerException.Message));
  53. }
  54. }
  55. }
  56. /// <summary>
  57. /// DAL方法
  58. /// </summary>
  59. /// <param name="methodFullName"></param>
  60. /// <param name="methodParameters"></param>
  61. /// <returns></returns>
  62. public static object RunDALMethod(string methodFullName, params object[] methodParameters)
  63. {
  64. IList<string> names = methodFullName.Split('.').ToList();
  65. if (names.Count <= 2)
  66. {
  67. throw (new Exception("方法名输入错误。"));
  68. }
  69. string methodName = names.Last();
  70. names.RemoveAt(names.Count - 1);
  71. string className = string.Join(".", names);
  72. string classShortName = names.Last();
  73. var classType = Assembly.Load("EMIS.DataLogic").GetType(className);
  74. using (var container = AutofacHelper.Container.BeginLifetimeScope())
  75. {
  76. var myClass = container.Resolve(classType);
  77. var myMethod = myClass.GetType().GetMethod(methodName);
  78. try
  79. {
  80. return myMethod.Invoke(myClass, methodParameters);
  81. }
  82. catch (Exception ex)
  83. {
  84. throw (new Exception(ex.InnerException.Message));
  85. }
  86. }
  87. }
  88. }
  89. }