这个问题的答案是由 Kevin 在MEF 讨论列表上提供的。事实证明,可以使用以下代码片段从 MEF ExportDefinition和ImportDefinition数据结构中提取所有需要的信息。
第一步是将程序集类型加载到目录中。然后为目录中的每个零件迭代导入和导出定义。导出定义只能放在类型、方法、属性和字段上(我的代码目前忽略了这些)。因此,可以使用以下代码来处理导出。
var exports = new List<Tuple<string, MemberInfo>>();
foreach (var export in part.ExportDefinitions)
{
var memberInfo = ReflectionModelServices.GetExportingMember(export);
Tuple<string, MemberInfo> exportDefinition = null;
switch (memberInfo.MemberType)
{
case MemberTypes.Method:
exportDefinition = new Tuple<string, MemberInfo>(export.ContractName, memberInfo.GetAccessors().First() as MethodInfo);
break;
case MemberTypes.NestedType:
case MemberTypes.TypeInfo:
exportDefinition = new Tuple<string, MemberInfo>(export.ContractName, memberInfo.GetAccessors().First() as Type);
break;
case MemberTypes.Property:
// this is a bit ugly because we assume that the underlying methods for a property are named as:
// get_PROPERTYNAME and set_PROPERTYNAME. In this case we assume that exports always
// have a get method.
var getMember = memberInfo.GetAccessors().Where(m => m.Name.Contains("get_")).First();
var name = getMember.Name.Substring("get_".Length);
var property = getMember.DeclaringType.GetProperty(name);
exportDefinition = new Tuple<string, MemberInfo>(export.ContractName, property);
break;
default:
throw new NotImplementedException();
}
exports.Add(exportDefinition);
}
为了处理只能放在属性、参数和字段(再次被忽略)上的导入,可以使用以下代码:
public void ExtractImports()
{
var imports = new List<Tuple<string, string>>();
foreach (var import in part.ImportDefinitions)
{
SerializedImportDefinition importDefinition = !ReflectionModelServices.IsImportingParameter(import)
? importDefinition = CreatePropertyImport(import)
: importDefinition = CreateConstructorParameterImport(import);
}
}
private Tuple<string, string> CreatePropertyImport(ImportDefinition import)
{
var memberInfo = ReflectionModelServices.GetImportingMember(import);
if (memberInfo.MemberType != MemberTypes.Property)
{
throw new ArgumentOutOfRangeException("import");
}
// this is a bit ugly because we assume that the underlying methods for a property are named as:
// get_PROPERTYNAME and set_PROPERTYNAME. In this case we assume that imports always
// have a set method.
var getMember = memberInfo.GetAccessors().Where(m => m.Name.Contains("set_")).First();
var name = getMember.Name.Substring("set_".Length);
var property = getMember.DeclaringType.GetProperty(name);
return new Tuple<string, string>(import.ContractName, property.ToString());
}
private Tuple<string, string> CreateConstructorParameterImport(ImportDefinition import)
{
var parameterInfo = ReflectionModelServices.GetImportingParameter(import);
return new Tuple<string, string>(import.ContractName, parameterInfo.Value.ToString());
}
请注意,似乎无法通过方法参数提供导入,因此上面的代码不支持这些。
处理完所有导出和导入后,将存储的MemberInfo对象序列化为字符串格式就是一个简单的问题。