![](/img/trans.png)
[英]CompositionContainer: How can I get the source class from an exported value
[英]How can I get a MEF exported value by a class name?
我有一個稱為MainWindow
的窗口和一個稱為MainWindowViewModel
的視圖模型。
我想調查一下MEF的容器,看看是否可以找到<WindowName>ViewModel
。
我的代碼是:
CompositionContainer container;
var catalog = new AssemblyCatalog(typeof(App).Assembly);
container = new CompositionContainer(catalog);
container.ComposeParts(this);
container.SatisfyImportsOnce(this);
我看到了方法
container.GetExports(Type, Type, String)
但它只允許我導出第一個Type
參數。 我只有一個字符串名稱。
我想做類似的事情
allExports.FirstOrDefault(e => e.GetType().Name.StartsWith(something))
有沒有一種方法可以通過string name
獲取導出的值?
由於allExports是IEnumerable <Lazy <T >>,因此如果不創建關聯值(通過調用.Value)然后檢查值類型,就無法獲取每個導出的類型。 創造所有價值並不是一件好事。 通過分析typeof(Lazy <T>),您可以獲得的只是typeof(T),僅此而已。
元數據是一個很好的方法:
[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; }
}
接口為:
public interface IViewModelMetadata
{
Type DeclaredType { get; }
}
然后您使用導出:
[ExportViewModel(typeof(MyViewModel))]
public class MyViewModel: BaseViewModel, IViewModel
{
[...]
}
然后使用關於元數據的where子句檢索它
IViewModel vm = container.GetExports<IViewModel, IViewModelMetadata>().Where(i => i.Metadata.DeclaredType == typeof(MyViewModel)).Select(i => i.Value).FirstOrDefault();
或搭配
i => i.Metadata.DeclaredType.Name == "mysearchedViewModel"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.