C# - 加载 dll 并创建实例

标签 c# dll interface

我遇到了一种情况,我需要知道如何以最好的方式处理它。

我有一个应用程序 (MVC3),并且我有几个集成。我有一个接口(interface)“IntegrationInterface”,每个集成都实现它。 我想加载集成的 dll,创建它们的列表,然后运行一个循环,为列表中的每个集成运行一个方法。

例如 - 假设我集成了 facebook、myspace 和 twitter(对于我的应用程序),每次用户在我的应用程序中发布消息时,我想在他/她的 facebook、myspace 和 twitter 上发布消息。

我不希望代码知道我有哪些集成,所以如果明天我要为 google+ 创建一个新的集成,我只需要添加一个新的 DLL,而无需更改我的应用程序的代码。

我怎样才能做到这一点?

最佳答案

首先,您必须找到所有相关的 dll 和类:

loadedIntegrations.Clear();
if (!Directory.Exists(path))
    return;
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] files = di.GetFiles("*.dll");
foreach (var file in files)
{
    Assembly newAssembly = Assembly.LoadFile(file.FullName);
    Type[] types = newAssembly.GetExportedTypes();
    foreach (var type in types)
    {
        //If Type is a class and implements the IntegrationInterface interface
        if (type.IsClass && (type.GetInterface(typeof(IntegrationInterface).FullName) != null))
            loadedIntegrations.Add(type);
    }
}

loadedIntegrations类型为List<Type> 。然后您可以实例化每个集成并调用其方法:

foreach(var integrationType in loadedIntegrations)
{
    var ctor = integrationType.GetConstructor(new Type[] { });
    var integration = ctor.Invoke(new object[] { }) as IntegrationInterface;
    //call methods on integration
}

关于C# - 加载 dll 并创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11491431/

相关文章:

c# - "Authentication failed because the remote party has closed the transport stream"使用 FluentFTP 通过 TLS/SSL 传输到/从 FTP 服务器时

c# - 我们如何在 C# 中从 C++ DLL 获取所有方法?

c++ - 在 dll 导出函数中使用 std::vector 的含义

c# - 罗斯林-CodeDom : HowTo dynamically compile Code to Universal-Windows-Library

java - 如果参数是同一接口(interface)的不同实现,compareTo() 应该返回什么?

c# - ReSharper 9.2 为具有事件名称的 nameof 生成警告

c# - 在 ASP .NET MVC 中更改角色权限

C# 和接口(interface) - 显式与隐式

c# - 如何在 string[][] 中以不同的顺序删除相同的值?

c# - 多态性不适用于 C# 中泛型类的调用