Advertisement
ivandrofly

RawCoding: Plugin Architecture

Apr 11th, 2023 (edited)
1,198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.19 KB | None | 0 0
  1. // See https://aka.ms/new-console-template for more information
  2.  
  3. using System.Reflection;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.Loader;
  6. using PluginSDK;
  7.  
  8.  
  9. var app = new App();
  10. await app.Run();
  11.  
  12. Console.WriteLine("done");
  13.  
  14. public class App
  15. {
  16.     public App()
  17.     {
  18.     }
  19.  
  20.     ~App()
  21.     {
  22.     }
  23.  
  24.     public async Task Run()
  25.     {
  26.         var weakReference = await Process();
  27.  
  28.         for (int i = 0; i < 10 && weakReference.IsAlive; i++)
  29.         {
  30.             GC.Collect();
  31.             GC.WaitForPendingFinalizers();
  32.         }
  33.         Console.WriteLine($"unload successfully {!weakReference.IsAlive}");
  34.     }
  35.  
  36.     // https://youtu.be/g4idDjBICO8
  37.     // 13:15 - the reason for extracting into a method (... to use stack to clean up the resources)
  38.     [MethodImpl(MethodImplOptions.NoInlining)]
  39.     static async Task<WeakReference> Process()
  40.     {
  41.         // Console.WriteLine(Environment.CurrentDirectory);
  42.  
  43.         var fullPath = Path.GetFullPath(".\\Plugins\\FlexibleApp.Plugin.dll");
  44.  
  45.         // fails to work
  46.         // var pluginFile = ".\\Plugins\\FlexibleApp.Plugin.dll";
  47.  
  48.  
  49.         // note: by using this we are loading the assembly into the global context
  50.         var assembly = Assembly.LoadFile(fullPath);
  51.  
  52.         // note: this will create a separated context just like appdomain where you can
  53.         // create several domain and load assembly into them to keep thing separated
  54.         var assemblyContext = new AssemblyLoadContext("plugins", isCollectible: true); // true: enable unload
  55.         try
  56.         {
  57.             var assemblyNonGlobal = assemblyContext.LoadFromAssemblyPath(fullPath);
  58.             // assemblyNonGlobal
  59.             var entryPoint = assemblyNonGlobal.GetType("AppPlugin.EntryPoint");
  60.             IPluginSdk plugin = (IPluginSdk)Activator.CreateInstance(entryPoint);
  61.             await plugin.ExecuteAsync();
  62.         }
  63.         finally
  64.         {
  65.             // https://youtu.be/g4idDjBICO8
  66.             // 11:00 - explain the unload
  67.             assemblyContext.Unload();
  68.         }
  69.  
  70.         return new WeakReference(assemblyContext);
  71.     }
  72. }
  73.  
  74. // source
  75. // https://www.youtube.com/watch?v=g4idDjBICO8&ab_channel=RawCoding
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement