AssemblyUtils.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Microsoft.Extensions.DependencyModel;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. namespace Infrastructure.Helper
  7. {
  8. public static class AssemblyUtils
  9. {
  10. /// <summary>
  11. /// 获取应用中的所有程序集
  12. /// </summary>
  13. /// <returns></returns>
  14. public static IEnumerable<Assembly> GetAssemblies()
  15. {
  16. var compilationLibrary = DependencyContext.Default
  17. .CompileLibraries
  18. .Where(x => !x.Serviceable && x.Type == "project")
  19. .ToList();
  20. return compilationLibrary.Select(p => Assembly.Load(new AssemblyName(p.Name)));
  21. }
  22. /// <summary>
  23. /// 获取应用中的所有Type
  24. /// </summary>
  25. /// <returns></returns>
  26. public static IEnumerable<Type> GetAllTypes()
  27. {
  28. var assemblies = GetAssemblies();
  29. return assemblies.SelectMany(p => p.GetTypes());
  30. }
  31. //获取泛型类名
  32. public static Type GetGenericTypeByName(string genericTypeName)
  33. {
  34. Type type = null;
  35. foreach (var assembly in GetAssemblies())
  36. {
  37. var baseType = assembly.GetTypes()
  38. .FirstOrDefault(t => t.IsGenericType &&
  39. t.GetGenericTypeDefinition().Name.Equals(genericTypeName, StringComparison.Ordinal));
  40. if (baseType != null)
  41. {
  42. return baseType?.GetGenericTypeDefinition();
  43. }
  44. }
  45. return type;
  46. }
  47. public static bool IsDerivedFromGenericBaseRepository(this Type? type, Type genericBase)
  48. {
  49. while (type != null && type != typeof(object))
  50. {
  51. var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
  52. if (genericBase == cur)
  53. {
  54. return true;
  55. }
  56. type = type.BaseType;
  57. }
  58. return false;
  59. }
  60. }
  61. }