MEF - Best Practice
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:
Code Snippet
- public interface IFoo
- {
- void Write();
- }
-
- [Export(typeof(IFoo))]
- public class Foo : IFoo
- {
- }
-
- public class Bar
- {
- [Import]
- public IFoo Foo { get; private set; }
- }
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.
Code Snippet
- public class Bar : IPartImportsSatisfiedNotification
- {
- public IFoo Foo { get; private set; }
-
- [ImportMany]
- private IFoo[] FoosInternal { get; set; }
-
- public void OnImportsSatisfied()
- {
- if (FoosInternal == null || FoosInternal.Length == 0)
- throw new Exception("MEF composition find no IFoo");
- if (FoosInternal.Length > 1)
- throw new Exception("MEF composition find to many IFoo");
- }
- }
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.
Code Snippet
- public class Bar : IPartImportsSatisfiedNotification
- {
- [Import(AllowDefault=true)]
- public IFoo Foo { get; private set; }
-
- public void OnImportsSatisfied()
- {
- if (Foo == null)
- throw new Exception("MEF composition find no IFoo");
- }
- }
after the composition we can validate whether IFoo composition goes right.
Summary
MEF failure at the composition phase can be frustrating.
in this post I have tried to offer pattern to ease that pain.