Plugins and extensions

suggest change

A plugin system lets other people (or other teams, or you, later) add features to an application without rebuilding it. The host defines a contract, plugins implement it in separate assemblies, and the host discovers and loads those assemblies at run time.

In .NET (Core and later) this is built on three pieces:

This article builds a working plugin host step by step: loading, dependency isolation, the type identity trap, versioning the contract, unloading and hot reload, and plugins that register services with dependency injection. It uses the .NET 10 SDK. Note that C# extension methods are something else entirely: they're a compile-time feature for adding methods to existing types, not a way to extend a running program.

Project layout

A plugin system needs at least three projects:

Contracts/      class library: IPlugin and other shared types
Host/           console app: references Contracts, loads plugins
HelloPlugin/    class library: references Contracts, implements IPlugin
JsonPlugin/     class library: same, and uses a NuGet package

The host never references a plugin project. It only knows about the contract.

The contract

Keep the contract small. Every type in it is a promise to all plugin authors, and changing it later is painful:

namespace Contracts;

public interface IPlugin
{
    string Name { get; }
    string Description { get; }
    string Run(string input, IHostServices host);
}

public interface IHostServices
{
    string HostVersion { get; }
    void Log(string message);
}

IHostServices is how plugins talk back to the host. Give plugins an interface rather than direct access to host internals, so you can change the host's implementation freely.

Writing a plugin

A plugin is an ordinary class library that implements the contract. One assembly can hold any number of plugins:

using Contracts;

namespace HelloPlugin;

public class UpperPlugin : IPlugin
{
    public string Name => "upper";
    public string Description => "Converts text to upper case";

    public string Run(string input, IHostServices host)
    {
        host.Log($"upper called by host {host.HostVersion}");
        return input.ToUpperInvariant();
    }
}

public class ReversePlugin : IPlugin
{
    public string Name => "reverse";
    public string Description => "Reverses text";

    public string Run(string input, IHostServices host) =>
        new string(input.Reverse().ToArray());
}

The project file is where the important details are:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableDynamicLoading>true</EnableDynamicLoading>
  </PropertyGroup>

  <ItemGroup>
    <ProjectReference Include="..\Contracts\Contracts.csproj">
      <Private>false</Private>
      <ExcludeAssets>runtime</ExcludeAssets>
    </ProjectReference>
  </ItemGroup>

</Project>

The contract must not ship with the plugin. The host already has it, and a second copy breaks casts, as shown in the type identity section below.

A second plugin uses Newtonsoft.Json 12, while the host itself uses Newtonsoft.Json 13:

<ItemGroup>
  <ProjectReference Include="..\Contracts\Contracts.csproj">
    <Private>false</Private>
    <ExcludeAssets>runtime</ExcludeAssets>
  </ProjectReference>
  <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
using Contracts;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace JsonPlugin;

public class PrettyJsonPlugin : IPlugin
{
    public string Name => "json";
    public string Description => "Pretty-prints JSON";

    public string Run(string input, IHostServices host)
    {
        var version = typeof(JsonConvert).Assembly.GetName().Version;
        host.Log($"json plugin uses Newtonsoft.Json {version}");
        return JToken.Parse(input).ToString(Formatting.Indented);
    }
}

Publish each plugin into its own subdirectory of the host's plugins folder:

$ dotnet publish HelloPlugin -o Host/bin/Debug/net10.0/plugins/HelloPlugin
$ dotnet publish JsonPlugin -o Host/bin/Debug/net10.0/plugins/JsonPlugin
$ cd Host/bin/Debug/net10.0 && ls plugins/*
plugins/HelloPlugin:
HelloPlugin.deps.json
HelloPlugin.dll
HelloPlugin.pdb
HelloPlugin.runtimeconfig.json

plugins/JsonPlugin:
JsonPlugin.deps.json
JsonPlugin.dll
JsonPlugin.pdb
JsonPlugin.runtimeconfig.json
Newtonsoft.Json.dll

No Contracts.dll in either folder, and JsonPlugin carries its own Newtonsoft.Json.dll. One folder per plugin is important: two plugins can depend on different versions of the same library, and their files can't sit side by side.

Loading plugins with AssemblyLoadContext

Each plugin gets its own AssemblyLoadContext (ALC). A load context is a scope for loaded assemblies: two contexts can each have their own version of Newtonsoft.Json loaded at the same time.

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

class PluginLoadContext : AssemblyLoadContext
{
    private readonly AssemblyDependencyResolver _resolver;

    public PluginLoadContext(string pluginPath, bool isCollectible = false)
        : base(Path.GetFileNameWithoutExtension(pluginPath), isCollectible)
    {
        _resolver = new AssemblyDependencyResolver(pluginPath);
    }

    protected override Assembly? Load(AssemblyName assemblyName)
    {
        // Types that cross the host/plugin boundary must come from the host.
        if (assemblyName.Name == "Contracts")
            return null;

        string? path = _resolver.ResolveAssemblyToPath(assemblyName);
        return path is null ? null : LoadFromAssemblyPath(path);
    }

    protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
    {
        string? path = _resolver.ResolveUnmanagedDllToPath(unmanagedDllName);
        return path is null ? IntPtr.Zero : LoadUnmanagedDllFromPath(path);
    }
}

When code in the plugin needs an assembly, the runtime calls Load:

AssemblyDependencyResolver reads the plugin's .deps.json and maps an assembly name to a file in the plugin's folder (or in the NuGet cache when running from a build directory). Framework assemblies like System.Linq aren't listed there, so they fall back to the default context automatically. LoadUnmanagedDll does the same for native libraries that a NuGet package carries, such as SQLite.

The loader scans the plugin folders, loads each main assembly and creates an instance of every public, concrete class that implements IPlugin:

using System.Reflection;
using Contracts;

static class PluginLoader
{
    public static List<IPlugin> LoadAll(string pluginsDir)
    {
        var plugins = new List<IPlugin>();
        foreach (string dir in Directory.GetDirectories(pluginsDir))
        {
            string dll = Path.Combine(dir, Path.GetFileName(dir) + ".dll");
            if (!File.Exists(dll))
                continue;
            try
            {
                plugins.AddRange(Load(dll));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"skipping {Path.GetFileName(dll)}: {ex.Message}");
            }
        }
        return plugins;
    }

    public static IEnumerable<IPlugin> Load(string dllPath)
    {
        var context = new PluginLoadContext(Path.GetFullPath(dllPath));
        Assembly asm = context.LoadFromAssemblyPath(Path.GetFullPath(dllPath));

        foreach (Type type in asm.GetExportedTypes())
        {
            if (type.IsClass && !type.IsAbstract && typeof(IPlugin).IsAssignableFrom(type))
                yield return (IPlugin)Activator.CreateInstance(type)!;
        }
    }
}

A broken plugin (a missing dependency, a constructor that throws) is skipped instead of taking the host down. Activator.CreateInstance needs a public parameterless constructor. See Instantiating classes that implement an interface e.g. plugin activation for the reflection basics.

The host:

using Contracts;
using Newtonsoft.Json;

var host = new HostServices();
var plugins = PluginLoader.LoadAll(Path.Combine(AppContext.BaseDirectory, "plugins"));

foreach (var p in plugins)
    Console.WriteLine($"{p.Name,-8} {p.Description}  [{p.GetType().Assembly.GetName().Name}]");

Console.WriteLine();
Console.WriteLine($"host uses Newtonsoft.Json {typeof(JsonConvert).Assembly.GetName().Version}");

var byName = plugins.ToDictionary(p => p.Name);
Console.WriteLine(byName["upper"].Run("hello plugins", host));
Console.WriteLine(byName["reverse"].Run("hello plugins", host));
Console.WriteLine(byName["json"].Run("""{"name":"ada","langs":["c#","f#"]}""", host));

class HostServices : IHostServices
{
    public string HostVersion => "1.0";
    public void Log(string message) => Console.WriteLine($"  [log] {message}");
}
upper    Converts text to upper case  [HelloPlugin]
reverse  Reverses text  [HelloPlugin]
json     Pretty-prints JSON  [JsonPlugin]

host uses Newtonsoft.Json 13.0.0.0
  [log] upper called by host 1.0
HELLO PLUGINS
snigulp olleh
  [log] json plugin uses Newtonsoft.Json 12.0.0.0
{
  "name": "ada",
  "langs": [
    "c#",
    "f#"
  ]
}

The host runs on Newtonsoft.Json 13 and the plugin on 12, in the same process, without conflict. Without separate load contexts, whichever version loaded first would win and the other side might fail with MissingMethodException.

The type identity trap

A type's identity in .NET is its name plus the assembly it was loaded from, including the load context. If Contracts.dll is loaded twice, once in the default context and once in the plugin's, you get two different IPlugin types with the same name.

To see this, build the plugin with a plain <ProjectReference> (so Contracts.dll is copied next to it) and remove the "Contracts" check from Load:

Type type = asm.GetType("HelloPlugin.UpperPlugin")!;
Type pluginIface = type.GetInterface("IPlugin")!;

Console.WriteLine($"implements IPlugin:  {typeof(IPlugin).IsAssignableFrom(type)}");
Console.WriteLine($"same name:           {pluginIface.FullName == typeof(IPlugin).FullName}");
Console.WriteLine($"host's Contracts:    {ContextOf(typeof(IPlugin))}");
Console.WriteLine($"plugin's Contracts:  {ContextOf(pluginIface)}");

object obj = Activator.CreateInstance(type)!;
var plugin = (IPlugin)obj;

static string ContextOf(Type t) =>
    System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(t.Assembly)!.Name!;
implements IPlugin:  False
same name:           True
host's Contracts:    Default
plugin's Contracts:  HelloPlugin
Unhandled exception. System.InvalidCastException: Unable to cast object of type
'HelloPlugin.UpperPlugin' to type 'Contracts.IPlugin'.

The class clearly implements an interface named Contracts.IPlugin, yet the cast fails. With the check back in place, both sides see the same type:

implements IPlugin:  True
same name:           True
host's Contracts:    Default
plugin's Contracts:  Default

The rule: every assembly whose types cross the boundary between host and plugin must be loaded only once, by the host. That's the contract assembly, plus any library whose types appear in the contract (for example Microsoft.Extensions.Logging.Abstractions if IHostServices exposed an ILogger). Everything else should be private to the plugin.

Private=false and ExcludeAssets=runtime keep the contract out of the plugin folder, and the explicit check in Load protects you when a plugin author gets the project file wrong. With the plain loop above, such a plugin would simply not be found, which is confusing to debug.

Versioning the contract

Plugins are compiled against one version of the contract and run against whatever version the host has. Two rules follow.

Additive changes only. Removing or changing a member breaks every plugin that uses it, with MissingMethodException or TypeLoadException at run time. Adding a member to an interface would also break existing implementations, unless you give it a default implementation:

public interface IPlugin
{
    string Name { get; }
    string Description { get; }
    string Run(string input, IHostServices host);

    // Added in 1.1. The default body keeps plugins built against 1.0 working.
    IReadOnlyList<string> Aliases => [];
}

Check the version before loading. A plugin built against a newer contract than the host has can't be loaded. Instead of failing with a FileNotFoundException deep inside GetExportedTypes, check the reference up front:

using System.Reflection;
using Contracts;

Version hostContracts = typeof(IPlugin).Assembly.GetName().Version!;
Console.WriteLine($"host Contracts {hostContracts}");

foreach (string dll in new[] { "plugins/HelloPlugin/HelloPlugin.dll", "futureplugins/JsonPlugin/JsonPlugin.dll" })
{
    string path = Path.GetFullPath(dll);
    var asm = new PluginLoadContext(path).LoadFromAssemblyPath(path);

    AssemblyName? wanted = asm.GetReferencedAssemblies().FirstOrDefault(a => a.Name == "Contracts");
    if (wanted?.Version is null || wanted.Version > hostContracts)
    {
        Console.WriteLine($"{asm.GetName().Name}: needs Contracts {wanted?.Version}, skipped");
        continue;
    }

    foreach (var t in asm.GetExportedTypes().Where(t => typeof(IPlugin).IsAssignableFrom(t)))
    {
        var p = (IPlugin)Activator.CreateInstance(t)!;
        Console.WriteLine($"{asm.GetName().Name}: built against Contracts {wanted.Version}, {p.Name} aliases: [{string.Join(", ", p.Aliases)}]");
    }
}
host Contracts 1.1.0.0
HelloPlugin: built against Contracts 1.0.0.0, upper aliases: []
HelloPlugin: built against Contracts 1.0.0.0, reverse aliases: []
JsonPlugin: needs Contracts 2.0.0.0, skipped

HelloPlugin was compiled against 1.0 and runs on the 1.1 host, getting the default Aliases. A request for an older version is satisfied by the newer assembly in the default context, but a request for a newer one isn't.

Set <Version> explicitly in the contract's project file and bump it on every release. Be careful with dotnet publish -p:Version=... on a plugin: the property flows to referenced projects too, so the plugin ends up referencing a contract version that doesn't exist.

Unloading plugins

A load context created with isCollectible: true can be unloaded, which frees the memory of its assemblies and releases the files. Unloading is cooperative: Unload() only starts the process, and the context is actually collected when nothing references it or anything loaded in it.

using System.Runtime.CompilerServices;
using System.Runtime.Loader;
using Contracts;

string dll = Path.GetFullPath("plugins/HelloPlugin/HelloPlugin.dll");

WeakReference contextRef = RunAndUnload(dll, "unload me");

for (int i = 0; contextRef.IsAlive && i < 10; i++)
{
    GC.Collect();
    GC.WaitForPendingFinalizers();
}
Console.WriteLine($"context alive after GC: {contextRef.IsAlive}");
Console.WriteLine($"HelloPlugin still loaded: {AppDomain.CurrentDomain.GetAssemblies().Any(a => a.GetName().Name == "HelloPlugin")}");

[MethodImpl(MethodImplOptions.NoInlining)]
static WeakReference RunAndUnload(string dllPath, string input)
{
    var context = new PluginLoadContext(dllPath, isCollectible: true);
    var asm = context.LoadFromAssemblyPath(dllPath);

    var type = asm.GetType("HelloPlugin.ReversePlugin")!;
    var plugin = (IPlugin)Activator.CreateInstance(type)!;
    Console.WriteLine(plugin.Run(input, null!));
    Console.WriteLine($"loaded in: {AssemblyLoadContext.GetLoadContext(asm)!.Name}, collectible: {context.IsCollectible}");

    context.Unloading += _ => Console.WriteLine("unloading...");
    context.Unload();
    return new WeakReference(context);
}
em daolnu
loaded in: HelloPlugin, collectible: True
unloading...
context alive after GC: False
HelloPlugin still loaded: False

All work with the plugin happens in a separate method marked NoInlining, so no local variable in the caller keeps a plugin object alive. The caller holds only a WeakReference to the context and runs the GC until it's gone.

If anything keeps a reference, unloading silently never completes. Adding one line, Leaked.Add(plugin); with Leaked a static list in the host, is enough:

em daolnu
loaded in: HelloPlugin, collectible: True
unloading...
context alive after GC: True
HelloPlugin still loaded: True

Common causes of contexts that won't unload:

Give your contract a cleanup hook (implement IDisposable or add a Stop() method) and call it before Unload(). Use dotnet-dump and dumpheap -type LoaderAllocator / gcroot to find what's keeping a context alive.

Hot reload

On Windows, LoadFromAssemblyPath keeps the file open for as long as the context lives, so you can't replace the plugin while it's loaded. LoadFromStream reads the assembly into memory and closes the file:

string dll = Path.GetFullPath("plugins/HelloPlugin/HelloPlugin.dll");
byte[] bytes = File.ReadAllBytes(dll);

var c1 = new PluginLoadContext(dll);
c1.LoadFromAssemblyPath(dll);
try
{
    File.WriteAllBytes(dll, bytes);
    Console.WriteLine("LoadFromAssemblyPath: file can be replaced");
}
catch (IOException ex)
{
    Console.WriteLine($"LoadFromAssemblyPath: {ex.Message}");
}

string copy = Path.GetFullPath("plugins/HelloPlugin/HelloPlugin.copy.dll");
File.Copy(dll, copy, overwrite: true);
var c2 = new PluginLoadContext(copy);
using (var fs = File.OpenRead(copy))
    c2.LoadFromStream(fs);
File.WriteAllBytes(copy, bytes);
Console.WriteLine("LoadFromStream: file can be replaced");
File.Delete(copy);
LoadFromAssemblyPath: The process cannot access the file '...\plugins\HelloPlugin\HelloPlugin.dll' because it is being used by another process.
LoadFromStream: file can be replaced

Combine LoadFromStream, a collectible context and a FileSystemWatcher, and the host can pick up a new build of a plugin without restarting:

using Contracts;

string dll = Path.GetFullPath("plugins/HelloPlugin/HelloPlugin.dll");
var host = new HostServices();
var reloader = new ReloadablePlugin(dll);
reloader.Reload();

using var watcher = new FileSystemWatcher(Path.GetDirectoryName(dll)!, "*.dll");
var debounce = new Timer(_ => reloader.Reload());
watcher.Changed += (_, _) => debounce.Change(500, Timeout.Infinite);
watcher.EnableRaisingEvents = true;

for (int i = 0; i < 12; i++)
{
    Console.WriteLine($"{DateTime.Now:HH:mm:ss} {reloader.Run("hello", host)}");
    Thread.Sleep(1000);
}

class ReloadablePlugin(string dllPath)
{
    private readonly Lock _lock = new();
    private PluginLoadContext? _context;
    private IPlugin? _plugin;

    public void Reload()
    {
        var context = new PluginLoadContext(dllPath, isCollectible: true);
        try
        {
            using var fs = File.OpenRead(dllPath);
            var asm = context.LoadFromStream(fs);
            var type = asm.GetExportedTypes().First(t => typeof(IPlugin).IsAssignableFrom(t));
            var plugin = (IPlugin)Activator.CreateInstance(type)!;

            lock (_lock)
            {
                _context?.Unload();
                (_context, _plugin) = (context, plugin);
            }
            Console.WriteLine($"loaded {type.FullName} ({File.GetLastWriteTime(dllPath):HH:mm:ss})");
        }
        catch (Exception ex)
        {
            context.Unload();
            Console.WriteLine($"reload failed, keeping the old version: {ex.Message}");
        }
    }

    public string Run(string input, IHostServices host)
    {
        lock (_lock)
            return _plugin!.Run(input, host);
    }
}

While it runs, change UpperPlugin to return input.ToUpperInvariant() + "!!!" and publish again:

loaded HelloPlugin.UpperPlugin (21:09:38)
21:09:41 HELLO
21:09:42 HELLO
...
21:09:48 HELLO
loaded HelloPlugin.UpperPlugin (21:09:48)
21:09:49 HELLO!!!
21:09:50 HELLO!!!

Details that matter:

Plugins and dependency injection

Apps built on Microsoft.Extensions.DependencyInjection (ASP.NET Core, the generic host) can let plugins register their own services. Add a startup interface to the contract:

public interface IPluginStartup
{
    void ConfigureServices(Microsoft.Extensions.DependencyInjection.IServiceCollection services);
}

The contract now exposes IServiceCollection, so the assembly that defines it (Microsoft.Extensions.DependencyInjection.Abstractions) crosses the boundary and must be shared too:

class PluginLoadContext : AssemblyLoadContext
{
    private static readonly HashSet<string> SharedAssemblies =
    [
        typeof(Contracts.IPlugin).Assembly.GetName().Name!,
        typeof(Microsoft.Extensions.DependencyInjection.IServiceCollection).Assembly.GetName().Name!,
    ];

    // constructor and LoadUnmanagedDll as before

    protected override Assembly? Load(AssemblyName assemblyName)
    {
        if (SharedAssemblies.Contains(assemblyName.Name!))
            return null;

        string? path = _resolver.ResolveAssemblyToPath(assemblyName);
        return path is null ? null : LoadFromAssemblyPath(path);
    }
}

A plugin can now use constructor injection, receive host services and keep its own classes internal:

using Contracts;
using Microsoft.Extensions.DependencyInjection;

namespace StatsPlugin;

public class Startup : IPluginStartup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<WordCounter>();
        services.AddSingleton<IPlugin, StatsCommand>();
    }
}

class WordCounter
{
    public int Count(string text) =>
        text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length;
}

class StatsCommand(WordCounter counter, IHostServices host) : IPlugin
{
    public string Name => "stats";
    public string Description => "Counts words";

    public string Run(string input, IHostServices _)
    {
        host.Log("stats got its dependencies from the container");
        return $"{counter.Count(input)} words, {input.Length} chars";
    }
}

The host runs each plugin's ConfigureServices, registers plain IPlugin classes directly, then builds the container. Calls into plugins are wrapped in try/catch, because a plugin's bug shouldn't crash the host:

using System.Reflection;
using Contracts;
using Microsoft.Extensions.DependencyInjection;

var services = new ServiceCollection();
services.AddSingleton<IHostServices, HostServices>();

foreach (string dir in Directory.GetDirectories("plugins"))
{
    string dll = Path.GetFullPath(Path.Combine(dir, Path.GetFileName(dir) + ".dll"));
    Assembly asm = new PluginLoadContext(dll).LoadFromAssemblyPath(dll);

    foreach (Type t in asm.GetExportedTypes().Where(t => t.IsClass && !t.IsAbstract))
    {
        if (typeof(IPluginStartup).IsAssignableFrom(t))
            ((IPluginStartup)Activator.CreateInstance(t)!).ConfigureServices(services);
        else if (typeof(IPlugin).IsAssignableFrom(t))
            services.AddSingleton(typeof(IPlugin), t);
    }
}

using ServiceProvider provider = services.BuildServiceProvider();
var host = provider.GetRequiredService<IHostServices>();
foreach (IPlugin plugin in provider.GetServices<IPlugin>())
{
    try
    {
        Console.WriteLine($"{plugin.Name,-8} {plugin.Run("the quick brown fox", host)}");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"{plugin.Name,-8} failed: {ex.GetType().Name}: {ex.Message}");
    }
}
  [log] upper called by host 1.0
upper    THE QUICK BROWN FOX
reverse  xof nworb kciuq eht
  [log] json plugin uses Newtonsoft.Json 12.0.0.0
json     failed: JsonReaderException: Error parsing boolean value. Path '', line 1, position 1.
  [log] stats got its dependencies from the container
stats    4 words, 19 chars

The JSON plugin got text that isn't JSON and threw. The host reported it and carried on.

For a declarative alternative with attributes ([Export], [ImportMany]) and metadata, there's MEF in the System.Composition package. See Dependency injection using MEF.

Limitations and security

If users only need to customize behavior with small amounts of code rather than ship compiled assemblies, consider embedding a scripting engine instead. See C# Script and Runtime Compile.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents