Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // See https://aka.ms/new-console-template for more information
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Runtime.Loader;
- using PluginSDK;
- var app = new App();
- await app.Run();
- Console.WriteLine("done");
- public class App
- {
- public App()
- {
- }
- ~App()
- {
- }
- public async Task Run()
- {
- var weakReference = await Process();
- for (int i = 0; i < 10 && weakReference.IsAlive; i++)
- {
- GC.Collect();
- GC.WaitForPendingFinalizers();
- }
- Console.WriteLine($"unload successfully {!weakReference.IsAlive}");
- }
- // https://youtu.be/g4idDjBICO8
- // 13:15 - the reason for extracting into a method (... to use stack to clean up the resources)
- [MethodImpl(MethodImplOptions.NoInlining)]
- static async Task<WeakReference> Process()
- {
- // Console.WriteLine(Environment.CurrentDirectory);
- var fullPath = Path.GetFullPath(".\\Plugins\\FlexibleApp.Plugin.dll");
- // fails to work
- // var pluginFile = ".\\Plugins\\FlexibleApp.Plugin.dll";
- // note: by using this we are loading the assembly into the global context
- var assembly = Assembly.LoadFile(fullPath);
- // note: this will create a separated context just like appdomain where you can
- // create several domain and load assembly into them to keep thing separated
- var assemblyContext = new AssemblyLoadContext("plugins", isCollectible: true); // true: enable unload
- try
- {
- var assemblyNonGlobal = assemblyContext.LoadFromAssemblyPath(fullPath);
- // assemblyNonGlobal
- var entryPoint = assemblyNonGlobal.GetType("AppPlugin.EntryPoint");
- IPluginSdk plugin = (IPluginSdk)Activator.CreateInstance(entryPoint);
- await plugin.ExecuteAsync();
- }
- finally
- {
- // https://youtu.be/g4idDjBICO8
- // 11:00 - explain the unload
- assemblyContext.Unload();
- }
- return new WeakReference(assemblyContext);
- }
- }
- // source
- // https://www.youtube.com/watch?v=g4idDjBICO8&ab_channel=RawCoding
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement