【问题标题】:Wpf load dll at runtimeWpf 在运行时加载 dll
【发布时间】:2017-12-26 10:54:15
【问题描述】:

我在 WPF 中创建了应用程序,每个客户端的应用程序的一部分都不同

当我将应用程序部署到新客户端时,我必须创建新类或修改旧类,因为每个客户端都有不同的业务逻辑。

对于 2 个客户端没有问题,但它们的数量越来越多。 我有想法为我的应用程序创建插件。 例如: 我创建了一个应用程序(核心),并且只将自定义 dll(插件)复制到磁盘上的特定文件夹中

这是我的问题,这是个好主意吗?考虑到一个客户端可能只有很少的插件,我不知道它是否足够高效。

我的样本:

    interface IST
{
    string Name { get; set; }
    string WorkRequest(string connection);
    void Start();
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        var plcConnectionString = "";
        string[] allPlugins = Directory.GetFiles(@"D:\app_plugins\", "*.dll", SearchOption.AllDirectories);

        foreach (var item in allPlugins)
        {
            Assembly myassembly = Assembly.LoadFrom(item);
            Type type = myassembly.GetType("appPlugins.ST");

            object instance = Activator.CreateInstance(type);
            MethodInfo[] methods = type.GetMethods();
            object res = methods[0].Invoke(instance, new object[] { plcConnectionString }); // WorkRequest
        }
    }
}

所有插件实现接口IST我可以用它代替object吗?

我用过: http://www.codingvision.net/miscellaneous/c-load-dll-at-runtime

【问题讨论】:

标签: c# wpf dll .net-assembly


【解决方案1】:

只有使用反射调用方法,别无选择。

object instance = Activator.CreateInstance(type);
MethodInfo[] methods = type.GetMethods();
object res = methods[0].Invoke(instance, new object[] { plcConnectionString });

例如,这里的methods[0] 是什么?

如果 IST 是核心库中的已知类型,并且插件 dll 中的类实现 IST,则进行强制转换:

IST instance = (IST)Activator.CreateInstance(type);
instance.Start();

现在方法调用变成了类型安全的

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多