【发布时间】:2012-11-19 10:40:15
【问题描述】:
我想知道如何设计应用程序,实际上是 Firefox 或 Chrome 等应用程序,您可以为它们下载附加组件并使用 ??!! 在.Net中怎么做???
【问题讨论】:
我想知道如何设计应用程序,实际上是 Firefox 或 Chrome 等应用程序,您可以为它们下载附加组件并使用 ??!! 在.Net中怎么做???
【问题讨论】:
【讨论】:
如何允许其他人为您的应用制作附加组件?
1>您创建一个DLL,其中有一个interface。这个interface 定义了一组您希望其他人定义和实现的方法、属性和事件。
插件开发者需要定义这个接口。这个DLL是你的应用程序和插件开发者需要的..
2>插件开发者将使用共享的DLL 并通过在其中定义方法或属性来实现接口。
3>您的应用现在将加载该插件并将其转换为共享 DLL 的 interface,然后调用所需的方法、属性,即接口中定义的任何内容..
您的应用如何获取插件?
您创建一个folder,您将在其中搜索plugins。这是其他plugins 将是installed 或placed 的文件夹。
例子
这是你的共享 dll
//this is the shared plugin
namespace Shared
{
interface IWrite
{
void write();
}
}
插件开发者
//this is how plugin developer would implement the interface
using Shared;//<-----the shared dll is included
namespace PlugInApp
{
public class plugInClass : IWrite //its interface implemented
{
public void write()
{
Console.Write("High from plugInClass");
}
}
}
这是你的程序
using Shared;//the shared plugin is required for the cast
class Program
{
static void Main(string[] args)
{
//this is how you search in the folder
foreach (string s in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*PlugIn.dll"))//getting plugins in base directory ending with PlugIn.dll
{
Assembly aWrite = Assembly.LoadFrom(s);
//this is how you cast the plugin with the shared dll's interface
Type tWrite = aWrite.GetType("PlugInApp.plugInClass");
IWrite click = (IWrite)Activator.CreateInstance(tWrite);//you create the object
click.write();//you call the method
}
}
}
【讨论】:
使用 MEF。
托管可扩展性框架 (MEF) 是 .NET 中的一个新库 从而可以更好地重用应用程序和组件。使用 MEF, .NET 应用程序可以从静态编译转变为 动态组成。如果您正在构建可扩展的应用程序, 可扩展框架和应用程序扩展,那么 MEF 适合您。
MEF 的有用链接。
http://www.codeproject.com/Articles/376033/From-Zero-to-Proficient-with-MEF
http://www.codeproject.com/Articles/232868/MEF-Features-with-Examples
【讨论】: