Dynamically load DLL files in C# project - how?

The MEF (Managed Extensibility Framework) Method:

You'll want to add references to System.ComponentModel.Composition to your projects that utilize the import/export functionality of MEF.

First, the bootstrapper/loader (in my case, I just added it to the Main class).

Program.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using MEFContract;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            var prgm = new Program();

            // Search the "Plugins" subdirectory for assemblies that match the imports.
            var catalog = new DirectoryCatalog("Plugins");
            using (var container = new CompositionContainer(catalog))
            {
                // Match Imports in "prgm" object with corresponding exports in all catalogs in the container
                container.ComposeParts(prgm);
            }

            prgm.DoStuff();

            Console.Read();
        }

        private void DoStuff()
        {
            foreach (var plugin in Plugins)
                plugin.DoPluginStuff();
        }

        [ImportMany] // This is a signal to the MEF framework to load all matching exported assemblies.
        private IEnumerable<IPlugin> Plugins { get; set; }
    }
}

The IPlugin interface is the contract between the imports & exports. All plugins will implement this interface. The contract is pretty simple:

IPlugin.cs:

namespace MEFContract
{
    public interface IPlugin
    {
        void DoPluginStuff();
    }
}

Finally, you can create as many plugins as you like in different assemblies. They must implement the contract interface and also be decorated with the "Export" attribute to indicate to MEF that they should be matched up with any corresponding imports. Then drop the dlls in a "Plugins" folder (this folder should reside in the same location as the executable). Here's a sample plugin:

Plugin.cs:

using System;
using System.ComponentModel.Composition;
using MEFContract;

namespace Plugin
{
    [Export(typeof(IPlugin))]
    public class Plugin : IPlugin
    {
        public void DoPluginStuff()
        {
            Console.WriteLine("Doing my thing!");
        }
    }
}

Let's assume for the sake of simplicity that all of the implementations of IPlugin have default constructors (public and no parameters).

That said, you really want to find all types that implement this interface and create an instance of them. You're on the right track somewhat, but you can simplify this tremendously with a little LINQ:

String path = Application.StartupPath;
string[] pluginFiles = Directory.GetFiles(path, "*.dll");


ipi = (
    // From each file in the files.
    from file in pluginFiles
    // Load the assembly.
    let asm = Assembly.LoadFile(file)
    // For every type in the assembly that is visible outside of
    // the assembly.
    from type in asm.GetExportedTypes()
    // Where the type implements the interface.
    where typeof(IPlugin).IsAssignableFrom(type)
    // Create the instance.
    select (IPlugin) Activator.CreateInstance(type)
// Materialize to an array.
).ToArray();

That said, you might be better off using a dependency injection framework; they usually allow for dynamic loading and binding to interface implementations in assemblies not referenced at compile time.

Also, while a bit convoluted (in my opinion), you might want to look at the System.AddIn namespaces, as they are built specifically for this purpose. However, the dependency injection route is usually much easier if you don't have to worry about version control of contracts and the like.

Tags:

C#

Plugins

Dll