MEF:从类型获取GetExportedValue吗? [英] MEF: GetExportedValue from Type?
本文介绍了MEF:从类型获取GetExportedValue吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用MEF,我可以创建和加载这样的类型:
Using MEF I can create and load a type like this:
var view = Container.GetExportedValue<MyView>();
现在我要做的是:
Type t = typeof(MyView);
var view = Container.GetExportedValue<t>();
(当然,该类型可能包含与MyView不同的内容).
(of course the type might contain something different than MyView).
使用泛型GetExportedValue不可能做到这一点-还有其他方法可以实现这一点吗?
This is not possible using the generics GetExportedValue<> - is there some other way to achieve this?
推荐答案
您可以使用反射.
这是一个示例:
You can use reflection.
Here is an example:
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<T> 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<T> method expects
Type[] genericTypeArray = new Type[] { type };
// add the generic types to the method
methodInfo = methodInfo.MakeGenericMethod(genericTypeArray);
// invoke GetExportedValue<type>()
return methodInfo.Invoke(container, null);
}
}
public interface IMessage
{
string Message { get; }
}
[Export(typeof(IMessage))]
public class MyMessage : IMessage
{
public string Message
{
get { return "test"; }
}
}
}
这篇关于MEF:从类型获取GetExportedValue吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文