0

I'm exporting a method using MEF with the attribute [Export] and I need to consume this method using the Container (obtaining the method using GetExports). GetExports returns an ExportedDelegate object that I have no idea how to extract the MethodInfo from. Inspecting with the debugger I see it as a private property and I'm tempted to extract it using reflection but it doesn't feel like the right way of doing this.

Any ideas?

This problem is different than this one. I'm not trying to use [Import], I have to obtain and consume the method from the Container.

Community
  • 1
  • 1
Hangarter
  • 582
  • 4
  • 12
  • Possible duplicate of [How to export & import functions and execute them with MEF?](http://stackoverflow.com/questions/3814839/how-to-export-import-functions-and-execute-them-with-mef) – FCin Dec 02 '16 at 10:34
  • It's not what I need mate, I need to run this methods programatically, getting them directly from the container. – Hangarter Dec 02 '16 at 10:53
  • Why is that? Can't you just import it. What's stopping you? – FCin Dec 02 '16 at 10:54
  • It's a very specific situation: there is a centralized method that captures webrequests and we are basically associating a route to a class, that can be any class in the system that implements the interface I'm searching for. Basically I don't know what the signature of the method will be! – Hangarter Dec 02 '16 at 10:56

1 Answers1

0

Alright guys so that was a tricky one but I'm leaving here as a reference.

All you have to do is to cast the value returned from MEF to a ExportedDelegate and call CreateDelegate the right way:

This sets the Import we want:

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();                       

This gets the methods of the objects found above (iterate objectsWithMethods in a foreach using objectsWithMethod):

 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();

And finally to get MethodInfo (which allows you to run the method) you use:

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

What also could be:

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

Hope it helps anyone!

Hangarter
  • 582
  • 4
  • 12