简体   繁体   中英

Dynamically load DLL files in C# project - how?

In my project I need to use plugins. But to use these in my project I need to import an reference of the plugin. Since I can't know how many or which plugins the project uses beforehand I would like to import them dynamically in my project.

    String path = Application.StartupPath;
    string[] pluginFiles = Directory.GetFiles(path, "*.dll");
    ipi = new IPlugin[pluginFiles.Length];
    Assembly asm;

        for (int i = 0; i < pluginFiles.Length; i++)
        {
            string args = pluginFiles[i].Substring(
                pluginFiles[i].LastIndexOf("\\") + 1,
                pluginFiles[i].IndexOf(".dll") -
                pluginFiles[i].LastIndexOf("\\") - 1);

            asm = Assembly.LoadFile(pluginFiles[i]);
            Type[] types = asm.GetTypes();

In this code example I searched all the .dll files and put them into a string list. But how can I now load all these .dll files? Or is there a way to use these .dll files without really importing them?

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.

I have an application which can not only load plugin at runtime, but also hot-load and unload them as user drop them in the folder, take them out or erase them. So, when I need to recompile my plugin, I don't need to re-launch my application. In my case, all plugin derive from the Plugin abstract, so they are easy to find in.DLL.

Here's my loading method:

private static void LoadPlugins(FileInfo file)
{
    try
    {
        Assembly assembly = Assembly.LoadFrom(file.FullName);

        foreach (Type type in assembly.GetTypes())
        {
            if (type.IsSubclassOf(typeof(Plugin)) && type.IsAbstract == false)
            {
                Plugin b = type.InvokeMember(null,
                                            BindingFlags.CreateInstance,
                                            null, null, null) as Plugin;
                plugins.Add(new PluginWrapper(b, file));
                b.Register();
            }
        }
    }
    catch (ReflectionTypeLoadException ex)
    {
        StringBuilder sb = new StringBuilder();
        foreach (Exception exSub in ex.LoaderExceptions)
        {
            sb.AppendLine(exSub.Message);
            if (exSub is FileNotFoundException)
            {
                FileNotFoundException exFileNotFound = exSub as FileNotFoundException;
                if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                {
                    sb.AppendLine("Fusion Log:");
                    sb.AppendLine(exFileNotFound.FusionLog);
                }
            }
            sb.AppendLine();
        }
        string errorMessage = sb.ToString();
        Log.Error("Plugins Manager", errorMessage);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM