简体   繁体   中英

Export and Import Delegate using Type with MEF

We are currently using MEF to import and export delegates by name.

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).

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

Check the part 2, it may be specially useful when he creates the custom export attributes with metadata.

Hope this helps, regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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