我正在使用MEF2,并阅读了一些关于mef1和mef2的教程。
到目前为止我发现的最好的一个是这个:http://www.codeproject.com/Articles/366583/MEF-Preview-Beginners-Guide
虽然我确实让导出工作得很好,但我真的想使用属性样式来实现它,因为在接口上使用InheritedExport似乎比在我声明的接口和容器约定之间来回往返要方便得多。
这是我的代码片段:
var convention = new ConventionBuilder();
convention.ForTypesDerivedFrom<IMainTabsControl>().Export<IMainTabsControl>();
convention.ForTypesDerivedFrom<IShell>().Export<IShell>().Shared();
// here is where i am struggeling.
convention.ForTypesMatching(type => typeof (ICrawlerKeyProvider).IsAssignableFrom(type)).Export(builder => builder.AsContractType(typeof(bool)));
var configuration = new ContainerConfiguration();
MefContainer = configuration.WithAssemblies(new []{ Assembly.GetExecutingAssembly(), }, convention).CreateContainer();所以有三种选择
据我所知,很容易做到:
但是使用ForTypesMatching,我似乎不能做我想做的事情,因为构建器变量没有可用的类型信息。
,我是不是想做一些奇怪的事情,在mf2中是不可能的,但在mf1?中却是可能的。
更新:
有趣的阅读:http://blog.slaks.net/2014-11-16/mef2-roslyn-visual-studio-compatibility/
发布于 2015-12-02 02:19:55
属性:
public class ExportAsAttribute : Attribute
{
public Type ContractType { get; set; }
public string ContactName { get; set; }
public ExportAsAttribute(Type contractType)
{
ContractType = contractType;
}
public ExportAsAttribute(Type contractType, string contactName)
{
ContactName = contactName;
ContractType = contractType;
}
}公约守则:
var allTypes = GetAllAssemblies().SelectMany(d => d.ExportedTypes);
foreach (var type in allTypes)
{
var attr = type.GetCustomAttribute<ExportAsAttribute>(true);
if (attr != null)
{
foreach (var derivedType in allTypes.Where(d => !d.IsAbstract && !d.IsInterface && type.IsAssignableFrom(d)))
{
if (string.IsNullOrEmpty(attr.ContactName))
{
convention.ForType(derivedType).Export(config => config.AsContractType(attr.ContractType));
}
else
{
convention.ForType(derivedType).Export(config => config.AsContractType(attr.ContractType).AsContractName(attr.ContactName));
}
}
}
}https://stackoverflow.com/questions/34033240
复制相似问题