Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 480
John_Sheares Avatar asked Sep 28 '10 16:09

John_Sheares


1 Answers

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; }
like image 142
Daniel Plaisted Avatar answered Oct 14 '22 12:10

Daniel Plaisted