决定在运行时调用什么dll [英] Decide what dll to call at runtime

查看:158
本文介绍了决定在运行时调用什么dll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Process.Start()方法根据需要启动特定的可执行文件。可执行文件是量身定制的,其中有很多这样的,路径&名称与他们所做的工作一起在数据库中。

I am using the Process.Start() method to launch a specific executable as needed. The executable is tailor-made, there are many of these, and the paths & names are in the database together with the job they do.

如果它们都实现了接口,是否有其他方法可以在进程中启动它们?我想能够调试它们并在调用它们时具有更好的类型安全性。

Is there another way to launch them in-process, if they all implement an interface? I want to be able to debug them and have better type safety when calling them.

我可以在每个解决方案中设置一个库项目,然后实例化该库并让它完成作业而不是可执行文件。问题是关于一种机制,允许我在接口上构建,然后在运行时按名称加载库。

I can set a library project in each solution, then instantiate that library and have it do the job instead of the executable. The question is about a mechanism that would allow me to build against the interface then load the library by its name at runtime.

推荐答案

如果需要自定义解决方案,可以使用以下内容。否则,您可以使用 Prism with Unity或MEF 中实现的模块化模式。

You can use something like the following if you want custom solution. Otherwise, you can use modular patterns implemented in Prism with Unity or MEF.

public interface IPlugin
{
    void Start();
}

// You can change this to support loading based on dll file name
// Use one of the other available Assembly load options
public void Load(string fullAssemblyName)
{
    var assembly = System.Reflection.Assembly.Load(fullAssemblyName);

    // Assuming only one class implements IPlugin 
    var pluginType = assembly.GetTypes()
               .FirstOrDefault(t => t.GetInterfaces()
               .Any(i=> i == typeof(IPlugin)));

    // Concrete class implementing IPlugin must have default empty constructor
    // for following instance creation to work
    var plugin = Activator.CreateInstance(pluginType) as IPlugin;
    plugin.Start();
}

这篇关于决定在运行时调用什么dll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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