如何创建只有当插件可以调用功能的插件机制? [英] How can I create a plugin mechanism that calls functions only when the plugin is available?

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

问题描述

很抱歉,如果我不太清楚,我有一个很难写这个问题。

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

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

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天全站免登陆