导出零件的 MEF 元数据
我希望使用 MEF 作为我正在构建的应用程序的插件系统。我希望每个组件都有一个标识符(GUID),我希望能够对其进行查找。但在处理导出的部件时,此 ID 也很有用。
有没有一种方法可以让我拥有一个包含 ID 以及导出部分的属性(或方法)的元数据属性,而不需要让开发人员填写两次或使用反射从属性中查找它?
I'm looking to use MEF for a plugin system for an application I'm building. Each component I want to have an identifier on (a GUID) which I want to be able to look up against. But this ID is also something that is useful when working with the exported part.
Is there a way that I can have a Metadata attribute which contains the ID as well as a property (or method) on the exported part, short of having developers fill it out twice or use reflection to find it from the attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它可能是 MEF 元数据属性和抽象基类的混合。我将我的插件契约定义为:
我强制
IPlugin
接口也继承我们的元数据契约IPluginMetadata
。接下来,我们可以创建一个自定义导出属性:您不需要使用元数据契约
IPluginMetadata
来修饰导出属性,因为 MEF 无论如何都会投影属性,但我更喜欢这样做,所以如果我确实对我的元数据合同进行了更改,那么我的导出属性也应该更新。没有伤害,没有犯规。完成此操作后,我们可以定义一个抽象基类,从中实现我们的插件契约:
然后我们可以通过抽象类的构造函数获取自定义属性,并相应地应用该属性。我们可以这样做:
而且:
我们可以看到
PluginId
通过导出的元数据以及我们插件的属性公开。该代码均未经测试,但我希望它能将您推向正确的方向。
It's likely to be a mixture of a MEF metadata attribute, and an abstract base class. I would define my plugin contract as something like:
I've enforced that the
IPlugin
interface also inherits our metadata contractIPluginMetadata
. Next, we can create a custom export attribute:You don't need to decorate the export attribute with the metadata contract
IPluginMetadata
, as MEF will project the properties anyway, but I prefer to do so, so if I do introduce changes to my metadata contract, then my export attribute should be updated too. No harm, no foul.Once we've done this, we can define an abstract base class from which to implement our plugin contract:
We can then grab the custom attribute through the abstract class's constructor, and apply the property accordingly. That we can do:
And also:
We can see that out
PluginId
is exposed both through exported metadata, as well as a property of our plugin.That code is all untested, but I hope it pushes you in the right direction.
将 GUID 放入常量中,并将其用于属性和元数据:
请注意,您不能使用
Guid
类型代替string
,因为它不是由const
关键字允许。Put the GUID in a constant, and use it for both a property and the metadata:
Note that you can't use the
Guid
type instead ofstring
, as that is not permitted by theconst
keyword.