CodeLoader.cs 1.9 KB

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