load and unload of assemblies dynamically

Dieter Oeschay 20 Reputation points
2026-04-14T11:56:08.2166667+00:00
Developer technologies | Windows Presentation Foundation
0 comments No comments

Answer accepted by question author

Nancy Vo (WICLOUD CORPORATION) 7,985 Reputation points Microsoft External Staff Moderator
2026-04-15T03:40:02.81+00:00

Hello @Dieter Oeschay

Thanks for your question.

To load and unload assemblies dynamically, I recommend using AssemblyLoadContext. You can refer to these following steps:

Load

using System.Reflection;
using System.Runtime.Loader;

public class PluginLoadContext : AssemblyLoadContext
{
    private AssemblyDependencyResolver _resolver;

    public PluginLoadContext(string pluginPath)
        : base(isCollectible: true)
    {
        _resolver = new AssemblyDependencyResolver(pluginPath);
    }

    protected override Assembly Load(AssemblyName assemblyName)
    {
        string assemblyPath = _resolver.ResolveAssemblyToPath(assemblyName);
        if (assemblyPath != null)
        {
            return LoadFromAssemblyPath(assemblyPath);
        }
        return null;
    }
}
  • Step 2: Create your plugin

Create a new Class Library project:

using System;

namespace MySimplePlugin
{
    public class Calculator
    {
        public string Name => "Calculator v2.0";

        public void Execute()
        {
            Console.WriteLine("Calculating 2 + 2 = 4");
        }

        public int Add(int a, int b)
        {
            return a + b;
        }
    }
}

string dllPath = @"C:\Plugins\MySimplePlugin.dll";
PluginLoadContext loadContext = new PluginLoadContext(dllPath);


Assembly assembly = loadContext.LoadFromAssemblyPath(dllPath);

Type pluginType = assembly.GetType("MySimplePlugin.Calculator");
object pluginInstance = Activator.CreateInstance(pluginType);

var nameProperty = pluginType.GetProperty("Name");
string name = (string)nameProperty.GetValue(pluginInstance);

var executeMethod = pluginType.GetMethod("Execute");
executeMethod.Invoke(pluginInstance, null);

Unload

  • Step 1: Clear all references to the plugin.
pluginInstance = null;
assembly = null;
loadContext.Unload();
  • Step 3: Force garbage collection.
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

I hope this addresses your question. If this response was helpful, please consider following the guidance to provide feedback.

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,856 Reputation points
    2026-04-15T14:03:11.2666667+00:00

    Note: this approach works for .net core. For .net 4.* you use a custom app domain. You can unload the app domain, which unloads all dlls loaded in that domain.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.