MEF:来自Type的GetExportedValue?

使用MEF我可以创建并加载这样的类型:

var view = Container.GetExportedValue(); 

现在我想要做的是:

 Type t = typeof(MyView); var view = Container.GetExportedValue(); 

(当然,类型可能包含与MyView不同的内容)。

使用genericsGetExportedValue 是不可能的 – 有没有其他方法来实现这一点?

你可以使用reflection。
这是一个例子:

 using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main() { AggregateCatalog catalog = new AggregateCatalog(); catalog.Catalogs.Add(new AssemblyCatalog(typeof(IMessage).Assembly)); CompositionContainer container = new CompositionContainer(catalog); Type t = typeof(IMessage); var m = container.GetExportedValue(t); } } public static class CompositionContainerExtension { public static object GetExportedValue(this ExportProvider container, Type type) { // get a reference to the GetExportedValue method MethodInfo methodInfo = container.GetType().GetMethods() .Where(d => d.Name == "GetExportedValue" && d.GetParameters().Length == 0).First(); // create an array of the generic types that the GetExportedValue method expects Type[] genericTypeArray = new Type[] { type }; // add the generic types to the method methodInfo = methodInfo.MakeGenericMethod(genericTypeArray); // invoke GetExportedValue() return methodInfo.Invoke(container, null); } } public interface IMessage { string Message { get; } } [Export(typeof(IMessage))] public class MyMessage : IMessage { public string Message { get { return "test"; } } } } 

请参阅此处接受的答案: 仅在给定Type实例的情况下从MEF容器导出