2010-09-28 7 views
14

Je crée une application qui importe plusieurs plugins. J'ai besoin de la capacité d'exécuter des fonctions qui sont implémentées dans chacun des plugins. Par exemple, j'ai besoin de faire quelque chose comme ça.Comment exporter et importer des fonctions et les exécuter avec MEF?

///////////////////////////////////////////////////////////////////////////////// 
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; 
} 
///////////////////////////////////////////////////////////////////////////////// 

Le problème est que je ne suis pas sûr de savoir comment définir l'importation et l'exportation & comment exécuter exactement la fonction.

Répondre

18

Vous pouvez importer les fonctions en tant que Func <> ou Action <> déléguer, en fonction de la signature de la fonction. Pour la première fonction, vous pouvez l'importer en IEnumerable<Lazy<Action>>. Le deuxième serait IEnumerable<Lazy<Func<string, string>>>.

Vous pouvez inclure un nom de contrat pour différencier les différentes fonctions avec la même signature. Une exportation de l'échantillon:

[Export("FunctionType")] 
public string Function(string value) 
{ 
    return value; 
} 

Et une importation correspondante:

[ImportMany("FunctionType")] 
public IEnumerable<Lazy<Func<string, string>>> ImportedFunctions { get; set; } 
+0

vous pas utiliser Si ImportMany? '[ImportMany (" FunctionType ")]' – mnn

+0

@mnn Merci, j'ai mis à jour le code –

Questions connexes