[英]How to export & import functions and execute them with MEF?
I am creating an application that imports several plugins. 我正在创建一个导入多个插件的应用程序。 I need the ability to execute functions that are implemented in each of the plugins.
我需要能够执行每个插件中实现的功能。 For example, I need to do something like this.
例如,我需要做这样的事情。
/////////////////////////////////////////////////////////////////////////////////
MainApp:
[ImportMany(?)]
public IEnumerable<Lazy<?>> PluginFunctions1 { get; set; }
[ImportMany(?)]
public IEnumerable<Lazy<?>> PluginFunctions2 { get; set; }
foreach (f1 in PluginFunctions1)
{
f1(); // execute Function1 from each plugin
}
foreach (f2 in PluginFunctions2)
{
string result = f2(val); // execute Function2 from each plugin
}
/////////////////////////////////////////////////////////////////////////////////
Plugin:
[export(?)]
public void Function1()
{
}
[export(?)]
public string Function2(string value)
{
return result;
}
/////////////////////////////////////////////////////////////////////////////////
Problem is that I am not sure how to define the import & export and how to exactly execute the function. 问题是我不确定如何定义导入和导出以及如何准确执行该功能。
You can import the functions as a Func<> or Action<> delegate, depending on the function signature. 您可以将函数作为Func <>或Action <>委托导入,具体取决于函数签名。 For the first function you could import it into
IEnumerable<Lazy<Action>>
. 对于第一个函数,您可以将其导入
IEnumerable<Lazy<Action>>
。 The second one would be IEnumerable<Lazy<Func<string, string>>>
. 第二个是
IEnumerable<Lazy<Func<string, string>>>
。
You may want to include a contract name to differentiate between different functions with the same signature. 您可能希望包含合同名称以区分具有相同签名的不同功能。 A sample export:
样本导出:
[Export("FunctionType")]
public string Function(string value)
{
return value;
}
And a corresponding import: 并进行相应的导入:
[ImportMany("FunctionType")]
public IEnumerable<Lazy<Func<string, string>>> ImportedFunctions { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.