CodeLoader.cs 1.9 KB

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