在C#项目中动态加载DLL文件-怎么做? [英] Dynamically load DLL files in C# project - how?

查看:68
本文介绍了在C#项目中动态加载DLL文件-怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我需要使用插件.但是要在我的项目中使用它们,我需要导入插件的引用.由于我不知道该项目预先使用了多少个插件,我想将其动态导入到我的项目中.

 字符串路径= Application.StartupPath;字符串[] pluginFiles = Directory.GetFiles(path,"* .dll");ipi =新的IPlugin [pluginFiles.Length];组装组件;为(int i = 0; i< pluginFiles.Length; i ++){字符串args = pluginFiles [i] .Substring(pluginFiles [i] .LastIndexOf("\\")+ 1pluginFiles [i] .IndexOf(.dll")-pluginFiles [i] .LastIndexOf("\\")-1);asm = Assembly.LoadFile(pluginFiles [i]);Type []类型= asm.GetTypes(); 

在此代码示例中,我搜索了所有 .dll 文件并将它们放入字符串列表.但是,现在如何加载所有这些 .dll 文件?还是有一种无需真正导入即可使用这些 .dll 文件的方法?

解决方案

为简单起见,我们假定 IPlugin 的所有实现均具有默认构造函数(公共且无参数).

也就是说,您确实想找到实现此接口的所有类型并创建它们的实例.您在正确的方向上有些走,但是您可以通过一点LINQ来极大地简化此操作:

 字符串路径= Application.StartupPath;字符串[] pluginFiles = Directory.GetFiles(path,"* .dll");ipi =(//从文件中的每个文件.来自pluginFiles中的文件//加载程序集.让asm = Assembly.LoadFile(file)//对于装配体中在外部可见的每种类型//程序集.从asm.GetExportedTypes()中的类型开始//类型实现接口的位置.其中typeof(IPlugin).IsAssignableFrom(type)//创建实例.选择(IPlugin)Activator.CreateInstance(类型)//实体化为数组.).ToArray(); 

也就是说,使用依赖项注入框架可能会更好.它们通常允许在编译时未引用的程序集中动态加载和绑定到接口实现.

另外,(在我看来)有点令人费解,但您可能想看看

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?

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.

这篇关于在C#项目中动态加载DLL文件-怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆