CodeLoader.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Runtime.Loader;
  6. namespace ET
  7. {
  8. public class CodeLoader: Singleton<CodeLoader>, ISingletonAwake
  9. {
  10. private AssemblyLoadContext assemblyLoadContext;
  11. private Assembly assembly;
  12. public void Awake()
  13. {
  14. Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
  15. foreach (Assembly assembly in assemblies)
  16. {
  17. if (assembly.GetName().Name == "Model")
  18. {
  19. this.assembly = assembly;
  20. break;
  21. }
  22. }
  23. Assembly hotfixAssembly = this.LoadHotfix();
  24. Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (World).Assembly, typeof(Init).Assembly, this.assembly, hotfixAssembly);
  25. World.Instance.AddSingleton<EventSystem, Dictionary<string, Type>>(types);
  26. IStaticMethod start = new StaticMethod(this.assembly, "ET.Entry", "Start");
  27. start.Run();
  28. }
  29. private Assembly LoadHotfix()
  30. {
  31. assemblyLoadContext?.Unload();
  32. GC.Collect();
  33. assemblyLoadContext = new AssemblyLoadContext("Hotfix", true);
  34. byte[] dllBytes = File.ReadAllBytes("./Hotfix.dll");
  35. byte[] pdbBytes = File.ReadAllBytes("./Hotfix.pdb");
  36. Assembly hotfixAssembly = assemblyLoadContext.LoadFromStream(new MemoryStream(dllBytes), new MemoryStream(pdbBytes));
  37. return hotfixAssembly;
  38. }
  39. public void Reload()
  40. {
  41. Assembly hotfixAssembly = this.LoadHotfix();
  42. Dictionary<string, Type> types = AssemblyHelper.GetAssemblyTypes(typeof (World).Assembly, typeof(Init).Assembly, this.assembly, hotfixAssembly);
  43. World.Instance.AddSingleton<EventSystem, Dictionary<string, Type>>(types, true);
  44. World.Instance.Load();
  45. Log.Debug($"reload dll finish!");
  46. }
  47. }
  48. }