2016-12-02 33 views
0

我正在導出一個使用MEF的屬性[Export]的方法,我需要使用Container使用此方法(使用GetExports獲取方法)。 GetExport返回一個ExportedDelegate對象,我不知道如何從中提取MethodInfo。 使用調試器進行檢查我將其看作私有屬性,我很想用反射來提取它,但它並不覺得這是正確的方式。如何使用編程方式使用通過MEF導出的方法?

任何想法?

此問題與this one不同。我沒有試圖使用[Import],我必須從Container獲取並使用該方法。

+0

可能出現[如何導出和導入函數並使用MEF執行它們]的副本(http://stackoverflow.com/questions/3814839/how-to-export-import-functions-and-execute-them-with -mef) – FCin

+0

這不是我需要的夥伴,我需要以編程方式運行這些方法,直接從容器中獲取它們。 –

+0

這是爲什麼?你不能直接導入它。什麼東西阻止你? – FCin

回答

0

好男人,所以這是一個棘手的,但我要離開這裏作爲參考。

所有你需要做的就是從MEF返回的值轉換爲ExportedDelegate並調用createDelegate方法的正確方法:

這臺導入我們想:

var importDefinition = new ImportDefinition(e => true, obj.GetType().FullName, ImportCardinality.ZeroOrMore, false, false); 

var objectsWithMethods = container.GetExports(importDefinition) 
       .Where(x => x.Value is IYourInterface) 
       .Select(x => x.Value) 
       .ToList();      

這得到的方法上述發現(在foreach使用objectsWithMethod迭代objectsWithMethods)對象:

var endPointsImportDefinition = new ImportDefinition(e => true, objectsWithMethod.GetType().FullName, ImportCardinality.ZeroOrMore, false, false); 
var endPoints = container.GetExports(endPointsImportDefinition) 
         .Where(x => x.Value is ExportedDelegate) 
         .Select(x => x.Value) 
         .ToList(); 

最後得到的MethodInfo(它允許您運行甲基OD)使用:

var endPointMethod = (endPoint as ExportedDelegate).CreateDelegate(typeof(Delegate)).GetMethodInfo(); 

什麼也可能是:

var endPointMethod = (endPoint as ExportedDelegate).CreateDelegate(typeof(Delegate)).Method; 

希望它能幫助任何人!

相關問題