您始终可以阅读目录以获取导出为给定类型的类型。
此代码不会从 [ImportMany] 中读取,而是您可以分配 IEnumerable,而不是类上的 ComposeParts。
此外,MEF 元数据是回避类型的,使用此元数据实际上需要实现接口。看起来你有一个名为 ViewModelMetadata 的类,它需要是一个接口。
public static class MEFExtensions
{
public static IEnumerable<Lazy<T, M>> GetExportsResolved<T, M>(this CompositionContainer mefContainer,
IUnityContainer unityContainer)
where T: class where M: class
{
// wrap the resolve around unity resolve then change type to T
return mefContainer.GetExportTypesWithMetadata<T, M>()
.Select(kv => new Lazy<T, M>(() => unityContainer.Resolve(kv.Key) as T, kv.Value));
}
public static IEnumerable<KeyValuePair<Type, M>> GetExportTypesWithMetadata<T, M>(
this CompositionContainer mefcontainer)
where T : class where M : class
{
// need to examine each type to see if they have the correct export attribute and metadata
foreach (var type in mefcontainer.GetExportTypes<T>())
{
// should just be one if more than one will throw exception
// metadata or export attribute has to implement the interface
var metadataAttribute =
type.GetCustomAttributes()
.SelectMany(
a =>
a.GetType()
.GetCustomAttributes()
.OfType<MetadataAttributeAttribute>()
.Concat<Attribute>(new[] { a }.OfType<ExportAttribute>()))
.OfType<M>().SingleOrDefault();
// if we found the correct metadata
if (metadataAttribute != null)
{
// return the lazy factory
yield return new KeyValuePair<Type, M>(type, metadataAttribute);
}
}
}
//Idea from http://www.codewrecks.com/blog/index.php/2012/05/08/getting-the-list-of-type-associated-to-a-given-export-in-mef/
public static IEnumerable<Type> GetExportTypes<T>(this CompositionContainer mefContainer)
where T : class
{
// look in the mef catalog to grab out all the types that are of type T
return mefContainer.Catalog.Parts.Where(part => part.ExportDefinitions
.Any(
def =>
def.Metadata.ContainsKey(
"ExportTypeIdentity") &&
def.Metadata["ExportTypeIdentity"]
.Equals(
typeof (T).FullName)))
.AsEnumerable()
.Select(part => ReflectionModelServices.GetPartType(part).Value);
}
}
您似乎也在尝试将其用作统一容器,最好只使用单元容器。我们目前使用 MEF 来查找所有注册 - 这些是导出属性,其中包含应如何注册的元数据。然后执行与上面类似的操作来填充统一容器而不是属性。
你会像这样使用它
ViewModelsLazy = mefContainer.GetExportsResolved<ViewModelBase, IViewModelMetadata>(unityContainer);
再次使用统一容器并执行类似的操作可能会更好
var regs = mefContainer.GetExportTypesWithMetadata<ViewModelBase, IViewModelMetadata>();
foreach (var reg in regs)
{
unityContainer.RegisterType(typeof (ViewModelBase), reg.Key, reg.Value.Name);
}
当你想要一个类解析时,你会去统一并做一个解析,将名称作为合同名称传递。