如何创建仅在插件可用时调用函数的插件机制? [英] How can I create a plugin mechanism that calls functions only when the plugin is available?

查看:30
本文介绍了如何创建仅在插件可用时调用函数的插件机制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果我不够清楚,我很难写这个问题.

Sorry if I am not clear enough, I've had a hard time writing this question.

我下载了一个开源软件.我想扩展功能,所以我想创建封装这些模块功能的模块,这些模块将是 .dll 文件.我想让一个完全独立于另一个:如果我在配置文件中将一个键设置为 true 并且文件夹中存在 DLL,则应该加载插件.

I downloaded an open source software. I would like to expand the functionalities so I would like to create modules that encapsulates the functionality these modules would be .dll files. I would like to have one completely independent from another: if I set a key to true in the config file and if the DLL is present on the folder, the plugin should be loaded.

问题是:如何动态调用插件(仅应用插件调用)?

如果我直接引用插件类,我将不得不引用插件dll,但我希望能够在没有插件的情况下运行核心软件.是否有任何设计模式或其他机制允许我仅在应用了插件的情况下加载和使用 DLL,并且仍然可以在没有插件的情况下运行核心软件?

If I reference the plugin classes directly, I would have to reference the plugin dll, but I want to be able to run the core software without the plugin. Is there any design pattern or other mechanism that would allow me to load and use the DLL only if the plugin is applied and still be possible to run the core software without the plugin?

推荐答案

有多种方法可以实现这一点,我将在这里介绍一个简单的解决方案.

There are various ways to achieve this and I will describe one simple solution here.

制作每个插件必须实现的通用接口,以便与核心应用程序集成.下面是一个例子:

Make a common interface that each plugin must implement in order to be integrated with core application. Here is an example:

// Interface which plugins must implement
public interface IPlugin
{
  void DoSomething(int Data);
}

// Custom plugin which implements interface
public class Plugin : IPlugin
{
  public void DoSomething(int Data)
  {
    // Do something
  }
}

要真正从 dll 加载插件,您需要使用反射,例如:

To actually load your plugin from dll, you will need to use reflection, for example:

// Load plugin dll and create plugin instance
var a = Assembly.LoadFrom("MyCustomPlugin.dll");
var t = a.GetType("MyCustomPlugin.Plugin");
var p = (IPlugin)Activator.CreateInstance(t);

// Use plugin instance later
p.DoSomething(123);

您可以为插件程序集和类使用某种命名约定以便您可以轻松加载它们.

You can use some kind of naming convention for your plugin assemblies and classes so that you can load them easily.

这篇关于如何创建仅在插件可用时调用函数的插件机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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