如何出口&导入功能并使用MEF执行它们? [英] How to export & import functions and execute them with MEF?

查看:180
本文介绍了如何出口&导入功能并使用MEF执行它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个导入几个插件的应用程序。我需要执行在每个插件中实现的功能的能力。例如,我需要做这样的事情。

  //////////////////////// ////////////////////////////////////////////////// ///// 
MainApp:
[ImportMany(?)]
public IEnumerable< Lazy<?>> PluginFunctions1 {get;组; }

[ImportMany(?)]
public IEnumerable< Lazy<?>> PluginFunctions2 {get;组;

foreach(Flugin in PluginFunctions1)
{
f1(); //从每个插件执行Function1
}

foreach(PluginFunctions2中的f2)
{
string result = f2(val); //从每个插件执行Function2
}

//////////////////////////// ////////////////////////////////////////////////// /
插件:
[export(?)]
public void Function1()
{
}

[export(?)]
public string Function2(string value)
{
return result;
}
////////////////////////////////////// ////////////////////////

问题是我不知道如何定义import&导出以及如何正确执行该功能。

解决方案

您可以将函数作为Func<或Action&取决于功能签名。对于第一个功能,您可以将其导入 IEnumerable< Lazy< Action>> 。第二个是 IEnumerable< Lazy&FunC< string,string>>>



希望包含一个合同名称来区分具有相同签名的不同功能。示例导出:

  [Export(FunctionType)] 
public string Function(string value)
{
返回值;
}

相应的导入:

  [ImportMany(FunctionType)] 
public IEnumerable< Lazy< Func< string,string>>> ImportedFunctions {get;组; }


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. For the first function you could import it into IEnumerable<Lazy<Action>>. The second one would be 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; }

这篇关于如何出口&amp;导入功能并使用MEF执行它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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