I'm gonna kick of a series on MEF partly for my own benefit, but maybe this will make sense to you as well. However, this won't be a beginners tutorial.
MEF ships with 3 types of part creation policies, Any, Shared and NonShared. By default all exports get the CreationPolicy.Any. What's a lesser known fact is that this allows the consumer -- imports -- to specify either CreationPolicy.Shared or CreationPolicy.NonShared.
Both attributes [Import] and [ImportMany] has a RequiredCreationPolicy property which let's you specify how the imports are satisfied. I tend to prefer to imply the correct behavior on the consumer side and not mandate that the producer has to think about it. With the default policy being CreationPolicy.Any a convenient factory pattern just imports with the CreationPolicy.NonShared. And if you're importing a collection you just don't have to worry about the composition failing, because if it's not working they're doing something wrong, it's not your problem.
Of course if you export a specific policy and import the other policy, the import is not satisfied which can lead to an unexpected exception being thrown.
No comments:
Post a Comment