lundi 17 juillet 2023

Why using AssemblyLoadContext.LoadFromAssemblyPath does not let me unload it later?

I am loading an assembly dynamically at run-time in .net 7 WPF app..

This context loader lets me to unload it later (see the MemoryStream): (taken from here: https://github.com/dotnet/runtime/issues/13226)

    public class CollectableAssemblyLoadContext : AssemblyLoadContext
    {
        private bool disposedValue;

        public CollectableAssemblyLoadContext(string name) : base(name, true) { }

        protected override Assembly Load(AssemblyName assemblyName) => null;

        public Assembly Load(byte[] rawAssembly)
        {
            using (var memoryStream = new MemoryStream(rawAssembly))
            {
                var assembly = LoadFromStream(memoryStream);
                return assembly;
            }
        }
    }

And this throws "not collectible assembly" exception on unload: (taken from here: https://learn.microsoft.com/en-gb/dotnet/core/tutorials/creating-app-with-plugin-support)

    public class PluginLoader : AssemblyLoadContext
    {
        private AssemblyDependencyResolver resolver;

        public PluginLoader(string pluginPath)
        {
            resolver = new AssemblyDependencyResolver(pluginPath);
        }

        protected override Assembly Load(AssemblyName assemblyName)
        {
            string assemblyPath = resolver.ResolveAssemblyToPath(assemblyName);
            if (assemblyPath != null)
            {
                return LoadFromAssemblyPath(assemblyPath);
            }

            return null;
        }
    }

Why? Is it by design or am I doing something wrong?





Aucun commentaire:

Enregistrer un commentaire