How to pass type from typename to GetExports in MEF?

I created a CompositionContainer, and now instead of giving types explicitly, I want to get the export using type names.

The code below works fine:

var p1Value = p.Container.GetExports<IPlugin, IPluginData>() .First(ip => ip.Metadata.Param.Equals( args[1], StringComparison.OrdinalIgnoreCase)) .Value .Execute(args.Skip(1).ToArray()); Console.WriteLine(p1Value); 

But I want to achieve the same if I have two string variables containing "IPlugin" and "IPluginData". Is there a way to pass types by name?

+4
source share
1 answer

Caution: this is not a common way to use MEF. But since you asked ... you can use GetExports overload , which accepts ImportDefinition .

To find out which contract name you should use for this type, you can call AttributedModelServices.GetContractName(typeof(IPlugin)) . Usually this is just the full type name.

The exact type of metadata is not important - all that matters is the metadata properties declared on it. You can describe them as in the requiredMetadata dictionary below.

 var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(catalog); string contractName = "SomeNamespace.IPlugin"; var requiredMetadata = new Dictionary<string, Type>(); requiredMetadata["Meta1"] = typeof(string); requiredMetadata["Meta2"] = typeof(int); var importDefinition = new ContractBasedImportDefinition( contractName, null, requiredMetadata, ImportCardinality.ZeroOrMore, false, true, CreationPolicy.Any); var exports = container.GetExports(importDefinition); Console.WriteLine(exports.Count()); Console.ReadKey(); 
+4
source

All Articles