CodeLoader.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 ass in assemblies)
  16. {
  17. if (ass.GetName().Name == "Model")
  18. {
  19. this.assembly = ass;
  20. break;
  21. }
  22. }
  23. Assembly hotfixAssembly = this.LoadHotfix();
  24. World.Instance.AddSingleton<CodeTypes, Assembly[]>(new[] { typeof (World).Assembly, typeof(Init).Assembly, this.assembly, hotfixAssembly });
  25. IStaticMethod start = new StaticMethod(this.assembly, "ET.Entry", "Start");
  26. start.Run();
  27. }
  28. private Assembly LoadHotfix()
  29. {
  30. assemblyLoadContext?.Unload();
  31. GC.Collect();
  32. assemblyLoadContext = new AssemblyLoadContext("Hotfix", true);
  33. byte[] dllBytes = File.ReadAllBytes("./Hotfix.dll");
  34. byte[] pdbBytes = File.ReadAllBytes("./Hotfix.pdb");
  35. Assembly hotfixAssembly = assemblyLoadContext.LoadFromStream(new MemoryStream(dllBytes), new MemoryStream(pdbBytes));
  36. return hotfixAssembly;
  37. }
  38. public void Reload()
  39. {
  40. Assembly hotfixAssembly = this.LoadHotfix();
  41. World.Instance.AddSingleton<CodeTypes, Assembly[]>(new[] { typeof (World).Assembly, typeof(Init).Assembly, this.assembly, hotfixAssembly }, true);
  42. World.Instance.Load();
  43. Log.Debug($"reload dll finish!");
  44. }
  45. }
  46. }