使用 MEF Preview 5 导入具有特定元数据的零件
我在 MEF 预览 5 中定义了一个导出,如下所示,
[ExportMetadata("Application", "CheckFolderApplication")]
[Export(typeof(ExtendedArtifactBase))]
public class CheckFolderArtifact2 : ExtendedArtifactBase
{ ...
然后我仅想要使用“Application”“CheckFolderApplication”元数据进行导入。 为此,我读取了所有导入内容,然后过滤结果。
[Import(typeof(ExtendedApplicationBase))]
private ExportCollection<IApplication> _applications { get; set; }
public IApplication GetApplication(string applicationName)
{
return _applications.Single(a => a.GetExportedObject().Name == applicationName).GetExportedObject();
}
这感觉确实效率低下。 如果我有数千个插件怎么办 - 我是否必须通过 MEF 读取所有插件才能获得具有正确元数据的插件? 如果是这样,你如何缓存结果?
I have a export defined as as follows in MEF preview 5
[ExportMetadata("Application", "CheckFolderApplication")]
[Export(typeof(ExtendedArtifactBase))]
public class CheckFolderArtifact2 : ExtendedArtifactBase
{ ...
Then I only want those imports with the "Application" "CheckFolderApplication" metadata. To currenly do that I read all the imports and then filter the result.
[Import(typeof(ExtendedApplicationBase))]
private ExportCollection<IApplication> _applications { get; set; }
public IApplication GetApplication(string applicationName)
{
return _applications.Single(a => a.GetExportedObject().Name == applicationName).GetExportedObject();
}
This feels really inefficient. What if I have thousands of plug-ins - do I have to read them all via MEF to just get one with the right metadata? If so how do you cache the result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,在这种情况下,您必须自己进行过滤。
要缓存结果,您可以将其存储在另一个私有变量中。 如果您想支持重组(您必须将导入属性的AllowRecomposition属性设置为true),那么您可以在您的类上实现IPartImportsSatisfiedNotification,并且每当设置导入时都会调用接口的OnImportsSatisfied方法。
Yes, in this case you will have to do the filtering yourself.
To cache the result, you can just store it in another private variable. If you want to support recomposition (you'd have to set the AllowRecomposition property of the import attribute to true), then you can implement IPartImportsSatisfiedNotification on your class and the interface's OnImportsSatisfied method will be called whenever the imports have been set.
我发现自己想做类似的事情。 我最终导入了 Lazy 并过滤元数据,希望能够避免提前实例化实际对象。
(对于强类型元数据 - 我还使用了该功能,您可以创建一个具有只读获取的接口 MyMetadataType,并传递该接口而不是设置 TMetadata = IDictionary)
我想 MEF 仍然必须至少读取所有“数千个插件”的元数据' 尽管...
I found myself wanting to do something similar. I eventually imported Lazy and filtering on the metadata, as hopefully a way of avoiding instantiating the actual objects ahead of time.
(And with strong typed metadata - I also used the feature where you can create an interface MyMetadataType with read only gets, and pass that instead of setting TMetadata = IDictionary)
I imagine MEF still has to read at least the metadata of all 'thousand plugins' though...