在 C# 项目中动态加载 DLL 文件 - 如何?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13253266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically load DLL files in C# project - how?
提问by Nanou Ponette
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 .dllfiles and put them into a string list.
But how can I now load all these .dllfiles? Or is there a way to use these .dllfiles without really importing them?
在这个代码示例中,我搜索了所有.dll文件并将它们放入一个字符串列表中。但是我现在如何加载所有这些.dll文件?或者有没有办法在.dll不真正导入它们的情况下使用这些文件?
采纳答案by casperOne
Let's assume for the sake of simplicity that all of the implementations of IPluginhave default constructors (public and no parameters).
为了简单起见,让我们假设所有的实现IPlugin都有默认构造函数(公共和无参数)。
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:
也就是说,您确实希望找到实现此接口的所有类型并创建它们的实例。您在某种程度上走在正确的轨道上,但是您可以使用一点 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.AddInnamespaces, as they are built specifically for this purpose. However, the dependency injection route is usually mucheasier if you don't have to worry about version control of contracts and the like.
此外,虽然有点令人费解(在我看来),但您可能想要查看System.AddInnamespaces,因为它们是专门为此目的构建的。但是,如果您不必担心合同的版本控制等,依赖注入路线通常会容易得多。
回答by LightStriker
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.
我有一个应用程序,它不仅可以在运行时加载插件,还可以在用户将它们放入文件夹、取出或删除它们时热加载和卸载它们。所以,当我需要重新编译我的插件时,我不需要重新启动我的应用程序。就我而言,所有插件都源自插件抽象,因此很容易在 .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);
}
}
回答by Cole Cameron
The MEF (Managed Extensibility Framework) Method:
MEF(托管扩展框架)方法:
You'll want to add references to System.ComponentModel.Compositionto your projects that utilize the import/export functionality of MEF.
您需要将System.ComponentModel.Composition 的引用添加到利用 MEF 导入/导出功能的项目中。
First, the bootstrapper/loader (in my case, I just added it to the Main class).
首先,引导程序/加载程序(在我的例子中,我只是将它添加到 Main 类中)。
Program.cs:
程序.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 接口是导入和导出之间的契约。所有插件都会实现这个接口。合约非常简单:
IPlugin.cs:
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:
最后,您可以在不同的程序集中创建任意数量的插件。它们必须实现合同接口,并且还使用“Export”属性进行修饰,以向 MEF 表明它们应该与任何相应的导入匹配。然后将 dll 放在“插件”文件夹中(该文件夹应与可执行文件位于同一位置)。这是一个示例插件:
Plugin.cs:
插件.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!");
}
}
}

