[英]How can I get a MEF exported value by a class name?
I have a window called MainWindow
and a viewmodel called MainWindowViewModel
. 我有一个称为
MainWindow
的窗口和一个称为MainWindowViewModel
的视图模型。
I want to look into MEF's container to see if I can find <WindowName>ViewModel
. 我想调查一下MEF的容器,看看是否可以找到
<WindowName>ViewModel
。
The code I have is: 我的代码是:
CompositionContainer container;
var catalog = new AssemblyCatalog(typeof(App).Assembly);
container = new CompositionContainer(catalog);
container.ComposeParts(this);
container.SatisfyImportsOnce(this);
I saw the method 我看到了方法
container.GetExports(Type, Type, String)
but it only allows me to get exports of the first Type
parameter. 但它只允许我导出第一个
Type
参数。 All I have is a string name. 我只有一个字符串名称。
I wanted to do something like 我想做类似的事情
allExports.FirstOrDefault(e => e.GetType().Name.StartsWith(something))
Is there a way I can get an exported value by a string name
? 有没有一种方法可以通过
string name
获取导出的值?
Since allExports is IEnumerable< Lazy< T >> you can't get each exported type without creating the associated value (by calling .Value), and then inspecting value type. 由于allExports是IEnumerable <Lazy <T >>,因此如果不创建关联值(通过调用.Value)然后检查值类型,就无法获取每个导出的类型。 And this is not really a good thing to create all values.
创造所有价值并不是一件好事。 All you can get is the typeof(T) by analyzing typeof(Lazy< T >), that's all.
通过分析typeof(Lazy <T>),您可以获得的只是typeof(T),仅此而已。
Metadata is the good way to go : 元数据是一个很好的方法:
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportViewModelAttribute : ExportAttribute, IViewModelMetadata
{
public ExportViewModelAttribute(Type declaredType)
: base(null, typeof(IViewModel))
{
this.DeclaredType = declaredType;
}
public Type DeclaredType { get; private set; }
}
with interface as : 接口为:
public interface IViewModelMetadata
{
Type DeclaredType { get; }
}
then you export with : 然后您使用导出:
[ExportViewModel(typeof(MyViewModel))]
public class MyViewModel: BaseViewModel, IViewModel
{
[...]
}
And then retreive it with a where clause on metadata 然后使用关于元数据的where子句检索它
IViewModel vm = container.GetExports<IViewModel, IViewModelMetadata>().Where(i => i.Metadata.DeclaredType == typeof(MyViewModel)).Select(i => i.Value).FirstOrDefault();
or with 或搭配
i => i.Metadata.DeclaredType.Name == "mysearchedViewModel"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.