简体   繁体   English

使用Type与MEF导出和导入代理

[英]Export and Import Delegate using Type with MEF

We are currently using MEF to import and export delegates by name. 我们当前正在使用MEF按名称导入和导出代表。

public delegate IThing ThingGenerator();

[Export("ThingGenerator")]
public IThing MyThingGenerator() { ... }

[ImportMany("ThingGenerator")]
public IEnumerable<ThingGenerator> ThingGenerators { get; set; }

For maintainability, we would like to import and export using types. 为了可维护性,我们想使用类型导入和导出。 However, we cannot seem to make this work. 但是,我们似乎无法完成这项工作。

[Export(typeof(ThingGenerator))]
public IThing MyThingGenerator() { ... }

[ImportMany(typeof(ThingGenerator))]
public IEnumerable<ThingGenerator> ThingGenerators { get; set; }

In some forms we get errors stating the exported function doesn't match the delegate type. 在某些形式中,我们会出错,指出导出的函数与委托类型不匹配。 In other scenarios the types don't seem to get exported. 在其他情况下,这些类型似乎没有导出。 Has anyone done this successfully? 有人成功做到了吗?

You can actually import and export by type, only in your case you should try exporting and importing a typeof(IThing) instead of typeof(ThingGenerator). 实际上,您可以按类型导入和导出,只有在这种情况下,才应尝试导出和导入typeof(IThing)而不是typeof(ThingGenerator)。

Usually the exported parts implement some interface (which can be an empty interface, which acts like a tag), so you can identify what you are importing, but it works also with types. 通常,导出的零件会实现某些接口(可以是一个空接口,其作用类似于标签),因此您可以识别要导入的内容,但它也适用于类型。

Here is a nice video tutorial to help you get started with MEF (it's in SilverLight but works also for WPF, and should also work for Winforms) Part 1 Part 2 这是一个很好的视频教程,可以帮助您开始使用MEF(它在SilverLight中,但也适用于WPF,也应该适用于Winforms) 第1 部分第2部分

Check the part 2, it may be specially useful when he creates the custom export attributes with metadata. 检查第2部分,当他使用元数据创建自定义导出属性时,它可能特别有用。

Hope this helps, regards 希望这会有所帮助,问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM