MEF – Best Practice
In this post I will offer MEF practice that may ease your MEF life.
one of the MEF headache is to understand what’s goes wrong,
when MEF reject the composition, you can read more about
MEF diagnostic in this post.
Most of the obscure loading failure happens when your Export dependencies doesn’t
satisfied. in those case you solely relay on the MEF error message which is not enough
in cases of deep dependencies graph.
It will normally occurs when you are using the Import attribute (not ImportMany).
let take the following test case:
class Bar importing IFoo, which mean that the composition will fail whenever
MEF find no valid IFoo export or find more than single IFoo export.
we can use 2 patterns:
- [ImportMany] which will handle both the case of no export and too many export.
- [Import(AllowDefault=true)] which cover the case of no export.
using ImportMany and the IPartImportsSatisfiedNotification pattern.
we can validate the composition right after the composition stage.
at the OnImportsSatisfied method you can check whether
you got the composition right (instead of letting the MEF infrastructure
doing this job).
in most cases it is enough to ignore the to many IFoo composition case
and to apply the [Import(AllowDefault=true)] pattern.
after the composition we can validate whether IFoo composition goes right.
MEF failure at the composition phase can be frustrating.
in this post I have tried to offer pattern to ease that pain.