在运行时动态加载DLL并创建接口实现的实例

时间:2020-06-05 14:54:51

标签: c# dll load

我有很多DLL连接器。每个DLL内部都有太多方法。但是每个DLL连接器都包含以下两种方法(byte [] Document = GetDocument(字符串,字符串,字符串);和byte [] Image = GetImage(字符串,字符串,字符串);)。

我想做的是: 1-在运行时选择DLL文件。 2-填充三个字符串。 3-将三个字符串传递到插入的DLL中的方法(上面提到的)以接收返回的文件。

我只想知道如何在DLL中调用方法。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您必须使用反射(当然)。
看一下Assembly类。

您可以例如使用Assembly.LoadFileAssembly.LoadFrom加载程序集。
要激活组件中包含的类型以调用其成员,可以使用Assembly.CreateInstance

Assembly assembly = Assembly.LoadFile("C:\bin\runtime.dll");
TypeInsideAssembly instanceOfTypeInsideAssembly = (TypeInsideAssembly) assembly.CreateInstance(typeOf(TypeInsideAssembly));
instanceOfTypeInsideAssembly.InvokeMethod(params);

如果构造函数需要参数,则可以使用适当的overload CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])

示例

下面的通用示例使用反射来创建位于指定程序集中的TBase实例,期望使用无参数构造函数。 TBase可以是一个类(基类)或接口。
不是public或未定义无参数构造函数的类型将被忽略。

private IEnumerable<TBase> GetInstancesOf<TBase>(string assemblyFilePath)
{
  var assembly = Assembly.LoadFile(assemblyFilePath);

  // Get all public types that are defined in this assembly
  Type[] publicTypes = assembly.GetExportedTypes();

  // Filter all public types in assembly and return only types...
  IEnumerable<TBase> documentProviders = publicTypes

    // ...that are not an interface (as we can't create instances of interfaces)...
    .Where(publicType => !publicType.IsInterface 

      // ...AND that are not an abstract class (as we can't create instances of abstract types)...
      && !publicType.IsAbstract 

      // ...AND that have a public parameterless constructor...
      && publicType.GetConstructor(Type.EmptyTypes) != null 

      // ...AND are a subtype of TBase. Note that TBase can be a base class or interface 
      && typeof(TBase).IsAssignableFrom(publicType))

    // Take each collected type and create an instance of those types
    .Select(concreteInterfaceType => assembly.CreateInstance(concreteInterfaceType.FullName))

    // Since CreateInstance() returns object, cast each created instance to the common subtype TBase
    .Cast<TBase>();

  return documentProviders;
}

用法

private void HandleDocuments(string assemblyFilePath)
{
  foreach (IClientMethods documentProvider in GetInstancesOf<IClientMethods>(assemblyFilePath))
  {        
    byte[] document = documentProvider.GetDocument(...);
  }
}