How to reference a DLL on runtime?

后端 未结 6 965
有刺的猬
有刺的猬 2020-12-08 23:43

I\'m building an application with WPF and C#, basically I want to allow anyone to create a dll and put it into a folder (similar to plugins). The application will take all t

6条回答
  •  时光取名叫无心
    2020-12-09 00:25

    The answers above pretty much give you what you need. You can try to load all dlls to be plugged into your app when the program starts up:

    // note: your path may differ, this one assumes plugins directory where exe is executed
    var pluginsDirectory = Path.Combine(AppContext.BaseDirectory, "plugins");
    if (Directory.Exists(pluginsDirectory))
    {
        var dllPaths = Directory.GetFiles(pluginsDirectory);
        if (dllPaths.Count() > 0)
        {
            foreach (var dllPath in dllPaths)
            {
                Assembly.LoadFrom(Path.Combine("plugins", Path.GetFileName(dllPath)));
            }
        }
        else
        {
            // warn about no dlls
        }
    }
    else
    {
        // warn about no plugins directory
    }
    

    How to reference the dll and its types:

    // if dll file name is My.Plugin.Assembly.ShortName.dll, then reference as follows
    var pluginAssembly = Assembly.Load("My.Plugin.Assembly.ShortName");
    var typesInAssembly = pluginAssembly.GetExportedTypes();
    var instanceType = typesInAssembly.FirstOrDefault(t => t.Name == "MyClassName");
    var instance = Activator.CreateInstance(instanceType, new object[] { "constructorParam1", "constructorParam2" });
    instanceType.InvokeMember("MyMethod", BindingFlags.InvokeMethod, null, instance, new object[] { "methodParam1", "methodParam2" });
    

    You may need to tell your app configuration to probe your plugins directory. I'm assuming one child directory of plugins, you can probe a list of subdirectory paths.

    ...
    
        
    ...
    

    You will need something to tell you which type to implement (perhaps configuration mapping). The interface, as best I can tell, will just provide a contract all the plugins implement to provide an expected method to invoke via reflection.

提交回复
热议问题