TypeLoader.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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.refGUID);
  62. if (dependencyType == null)
  63. throw new Exception("Cannot find dependency type.");
  64. dependencyTypes.Add(dependencyType);
  65. }
  66. return dependencyTypes;
  67. }
  68. }
  69. }