Can I get a list of Type without instantiating using MEF?
-
2010年2月20日 20:21I'd like to get a list of Type of add-ins without instantiating. Is this possible with MEF?
I found Lazy<T> could be a solution, but couldn't find how to get Type from it. Maybe I'm missing something?
Any advices are greatly appreciated.
全部回复
-
2010年2月22日 6:09
Self resolved. In short, it's not supported.
Long version as a memo for myself, and for someone else who might be interested in this topic.
I wanted to list up type names in UI, and create as much instances as user wants. That was the original intention of the question.
It looks like it's in the plan for future, but this is not in .NET 4.
First, I still can't find a way to get a list of types. Current my understanding of MEF is that, in such cases, I should not depend on a list of types. MEF uses delegates to create instances, and a list of types should be abstracted as a list of delegates.
To create a list in UI, I think I should use ExportMetadata instead. With ExportMetadata attributes attached to each class, I can list them up from catalogs or from containers.
Second. Creating multiple instances is not supported in .NET 4. It used to be called PartCreator, and then ExportCreator as described in
http://mef.codeplex.com/wikipage?title=PartCreator&referringTitle=Guide
but also as described in the page, it's not part of .NET 4 unfortunatelly.
I still can use MEF primitives to do that though. Containers maintain lifetime of instances, but catalogs do not. So, I can either create a new container that has such capabilities, or call catalogs directly and create as many instances as I want. I have to maintain lifetime of created instances by myself.
Well. I'm not 100% sure the above is accurate, I'm still new to MEF. But since MEF is still v1, this makes sense to me. I'm happy that MEF provides primitives so I can write whatever it does not have today. Great.- 已标记为答案 Koji 2010年2月22日 6:11
-
2012年4月6日 17:10
Actually you can get this list from the Catalog
public static IEnumerable<Type> GetExportedTypes<T>() {
return catalog.Parts
.Select(part => ComposablePartExportType<T>(part))
.Where(t => t != null);
}
private static Type ComposablePartExportType<T>(ComposablePartDefinition part) {
if (part.ExportDefinitions.Any(
def => def.Metadata.ContainsKey("ExportTypeIdentity") &&
def.Metadata["ExportTypeIdentity"].Equals(typeof(T).FullName)))
{
return ReflectionModelServices.GetPartType(part).Value;
}
return null;
}The key point is the ReflectionModelService.GetPartType and a simple iteration on al the ComposablePartDefinition to find the parts that exports the desired interface or type.
Ricci Gian Maria. (http://www.codewrecks.com)

