← Back to Blog
Building a Plugin System in .NET with MEF

Building a Plugin System in .NET with MEF

Ever needed to extend your application without recompiling it? Maybe you want users to drop in new features as DLL files, or you're building a product that needs to support third-party extensions. That's exactly what MEF (Managed Extensibility Framework) was designed for.

In this article, I'll show you how to build a simple but powerful plugin system using MEF in .NET.

What is MEF?

MEF is a composition framework built into .NET that allows you to:

  • Discover plugins at runtime from a folder of DLLs
  • Hot-reload new plugins without restarting the application
  • Decouple your core application from plugin implementations

Think of it as a "plug and play" system for your code.

The Contract: Defining What Plugins Must Do

First, create a shared interface that all plugins must implement. This goes in a separate class library that both your main app and plugins will reference.

namespace MyApp.Plugins.Contracts;

public interface IDataExporter
{
    string Format { get; }
    string DisplayName { get; }
    string ContentType { get; }
    string FileExtension { get; }
    
    byte[] Export(ExportData data);
}

public record ExportData(string Title, IReadOnlyList<string> Items);

Keep this contract minimal and stable. Changing it means updating all plugins.

Creating a Plugin

Now let's build a CSV exporter plugin. This is a separate class library project that references only the contracts.

using System.ComponentModel.Composition;
using System.Text;
using MyApp.Plugins.Contracts;

[Export(typeof(IDataExporter))]
public class CsvExporter : IDataExporter
{
    public string Format => "csv";
    public string DisplayName => "CSV File";
    public string ContentType => "text/csv";
    public string FileExtension => ".csv";

    public byte[] Export(ExportData data)
    {
        var sb = new StringBuilder();
        sb.AppendLine($"# {data.Title}");
        sb.AppendLine("Number,Item");
        
        for (int i = 0; i < data.Items.Count; i++)
        {
            sb.AppendLine($"{i + 1},{EscapeCsv(data.Items[i])}");
        }
        
        return Encoding.UTF8.GetBytes(sb.ToString());
    }

    private static string EscapeCsv(string value)
    {
        if (value.Contains(',') || value.Contains('"'))
            return $"\"{value.Replace("\"", "\"\"")}\"";
        return value;
    }
}

The key here is the [Export(typeof(IDataExporter))] attribute. This tells MEF: "I'm an implementation of this interface, come find me."

The Plugin Loader

Here's where the magic happens. The PluginLoader class scans a folder for DLLs and loads any classes that export IDataExporter.

using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

public class PluginLoader : IDisposable
{
    private readonly DirectoryCatalog _catalog;
    private readonly CompositionContainer _container;
    private readonly Timer _pollingTimer;
    private readonly string _pluginsPath;
    private HashSet<string> _knownFiles = new();

    [ImportMany(typeof(IDataExporter), AllowRecomposition = true)]
    public IEnumerable<IDataExporter> Exporters { get; private set; } = [];

    public PluginLoader(string pluginsPath)
    {
        _pluginsPath = pluginsPath;
        
        if (!Directory.Exists(_pluginsPath))
            Directory.CreateDirectory(_pluginsPath);

        _catalog = new DirectoryCatalog(_pluginsPath, "*.dll");
        _container = new CompositionContainer(
            _catalog, 
            CompositionOptions.IsThreadSafe);
        
        _container.ComposeParts(this);
        _knownFiles = GetCurrentFiles();
        
        // Poll for new plugins every 5 seconds
        _pollingTimer = new Timer(
            CheckForChanges, 
            null, 
            TimeSpan.FromSeconds(5), 
            TimeSpan.FromSeconds(5));
    }

    private void CheckForChanges(object? state)
    {
        var currentFiles = GetCurrentFiles();
        
        if (!currentFiles.SetEquals(_knownFiles))
        {
            _catalog.Refresh();
            _knownFiles = currentFiles;
            Console.WriteLine($"Plugins reloaded: {Exporters.Count()} found");
        }
    }

    private HashSet<string> GetCurrentFiles() =>
        Directory.GetFiles(_pluginsPath, "*.dll").ToHashSet();

    public void Dispose()
    {
        _pollingTimer?.Dispose();
        _container?.Dispose();
        _catalog?.Dispose();
    }
}

Key Points

  • DirectoryCatalog scans a folder for DLLs containing MEF exports
  • CompositionContainer wires everything together
  • [ImportMany] collects all implementations of the interface
  • AllowRecomposition = true enables hot-reload when new DLLs are added
  • Polling checks for new files every 5 seconds (more reliable than FileSystemWatcher in Docker environments)

Using the Plugins

Now you can use the loaded plugins through a simple factory:

public class ExporterFactory
{
    private readonly PluginLoader _loader;

    public ExporterFactory(PluginLoader loader)
    {
        _loader = loader;
    }

    public IDataExporter? GetExporter(string format)
    {
        return _loader.Exporters
            .FirstOrDefault(e => 
                e.Format.Equals(format, StringComparison.OrdinalIgnoreCase));
    }

    public IEnumerable<IDataExporter> GetAll() => _loader.Exporters;
}

And call it from your application:

var factory = new ExporterFactory(pluginLoader);

// List available formats
foreach (var exporter in factory.GetAll())
{
    Console.WriteLine($"{exporter.Format}: {exporter.DisplayName}");
}

// Export data
var exporter = factory.GetExporter("csv");
if (exporter != null)
{
    var data = new ExportData("My Report", ["Item 1", "Item 2", "Item 3"]);
    var bytes = exporter.Export(data);
    File.WriteAllBytes($"report{exporter.FileExtension}", bytes);
}

Dependency Injection Setup

Register the plugin system in your DI container:

public static class PluginServiceExtensions
{
    public static IServiceCollection AddPlugins(
        this IServiceCollection services,
        string pluginsPath)
    {
        services.AddSingleton(new PluginLoader(pluginsPath));
        services.AddSingleton<ExporterFactory>();
        return services;
    }
}

Then in Program.cs:

builder.Services.AddPlugins("Plugins");

Project Structure

src/
├── MyApp/                      # Main application
├── MyApp.Plugins.Contracts/    # Shared interface (referenced by all)
└── Plugins/
    ├── MyApp.Plugins.Csv/      # CSV exporter plugin
    └── MyApp.Plugins.Json/     # JSON exporter plugin

Plugins/                        # Compiled DLLs go here
├── MyApp.Plugins.Csv.dll
└── MyApp.Plugins.Json.dll

Tips for Production

  • Keep contracts stable. Versioning plugin interfaces is painful.
  • Use polling over FileSystemWatcher. It's more reliable, especially in containers.
  • Handle composition errors gracefully. A bad DLL shouldn't crash your app.
  • Log plugin loading. You'll thank yourself when debugging.
  • Only copy what you need. Plugins only need the DLL, not .pdb or .deps.json files.

Conclusion

MEF makes it surprisingly easy to build a plugin architecture in .NET. With about 50 lines of code, you get automatic plugin discovery, hot-reload support, and clean separation between core app and extensions.

The pattern works great for export formats, payment providers, notification channels, or any feature where you want extensibility without recompilation.

Drop a DLL in the folder, wait 5 seconds, and your new feature is live.