TypeLoader.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. namespace BepInEx
  8. {
  9. public static class TypeLoader
  10. {
  11. /// <summary>
  12. /// Loads a list of types from a directory containing assemblies, that derive from a base type.
  13. /// </summary>
  14. /// <typeparam name="T">The specfiic base type to search for.</typeparam>
  15. /// <param name="directory">The directory to search for assemblies.</param>
  16. /// <returns>Returns a list of found derivative types.</returns>
  17. public static IEnumerable<Type> LoadTypes<T>(string directory)
  18. {
  19. List<Type> types = new List<Type>();
  20. Type pluginType = typeof(T);
  21. foreach (string dll in Directory.GetFiles(Path.GetFullPath(directory), "*.dll"))
  22. {
  23. try
  24. {
  25. AssemblyName an = AssemblyName.GetAssemblyName(dll);
  26. Assembly assembly = Assembly.Load(an);
  27. foreach (Type type in assembly.GetTypes())
  28. {
  29. if (type.IsInterface || type.IsAbstract)
  30. {
  31. continue;
  32. }
  33. else
  34. {
  35. if (type.BaseType == pluginType)
  36. types.Add(type);
  37. }
  38. }
  39. }
  40. catch (BadImageFormatException) { }
  41. }
  42. return types;
  43. }
  44. public static BepInPlugin GetMetadata(object Plugin)
  45. {
  46. return GetMetadata(Plugin.GetType());
  47. }
  48. public static BepInPlugin GetMetadata(Type PluginType)
  49. {
  50. object[] attributes = PluginType.GetCustomAttributes(typeof(BepInPlugin), false);
  51. if (attributes.Length == 0)
  52. return null;
  53. return (BepInPlugin)attributes[0];
  54. }
  55. public static IEnumerable<Type> GetDependencies(Type Plugin, IEnumerable<Type> AllPlugins)
  56. {
  57. object[] attributes = Plugin.GetCustomAttributes(typeof(BepInDependency), true);
  58. List<Type> dependencyTypes = new List<Type>();
  59. foreach (BepInDependency dependency in attributes)
  60. {
  61. Type dependencyType = AllPlugins.FirstOrDefault(x => GetMetadata(x)?.GUID == dependency.DependencyGUID);
  62. if (dependencyType == null)
  63. throw new MissingDependencyException("Cannot find dependency type.");
  64. dependencyTypes.Add(dependencyType);
  65. }
  66. return dependencyTypes;
  67. }
  68. }
  69. public class MissingDependencyException : Exception
  70. {
  71. public MissingDependencyException() : base()
  72. {
  73. }
  74. public MissingDependencyException(string message) : base(message)
  75. {
  76. }
  77. }
  78. }