MEF 2.0 - mini series: part 5 (Fluent export properties)
MEF 2.0 - mini series: part 5 (Fluent export properties)
this is the 5th post in the MEF 2.0 mini series.
you can see the following TOC for other posts in this series.
in this post I will cover the fluent property's export.

Exporting properties is a less known feature of MEF.
MEF 1 was supporting this feature by using the attribute model.
you could decorate a property with a [Export] attribute and then it become available for imports.
the following code demonstrate property exporting in MEF 1:
the Foo class is importing multiple SymmetricAlgorithm:
Code Snippet
- [Export]
- public class Foo
- {
- [ImportMany]
- public SymmetricAlgorithm[] CryptoProviders { get; private set; }
- }
and the CryptoComposer class is exporting a few symmetric algorithms:
Code Snippet
- [Export]
- public class CryptoComposer
- {
- [Export]
- public SymmetricAlgorithm Aes { get { return new AesManaged(); } }
- [Export]
- public SymmetricAlgorithm TripleDES { get { return new TripleDESCryptoServiceProvider(); } }
- [Export]
- public SymmetricAlgorithm RC2 { get { return new RC2CryptoServiceProvider(); } }
- }
with the following composition the Foo instance will have the CryptoComposer's symmetric algorithms:
Code Snippet
- var catalog = new AssemblyCatalog(typeof(Program).Assembly);
- var container = new CompositionContainer(catalog);
-
- var foo = container.GetExportedValue<Foo>();
so, how do we do it with the fluent export API?
to keep it simple I will leave the Foo class with the attribute model (we learned how to use fluent import in the previous post):
Code Snippet
- [Export]
- public class Foo
- {
- [ImportMany]
- public SymmetricAlgorithm[] CryptoProviders { get; private set; }
- }
-
- public class CryptoComposer
- {
- public SymmetricAlgorithm Aes { get { return new AesManaged(); } }
- public SymmetricAlgorithm TripleDES { get { return new TripleDESCryptoServiceProvider(); } }
- public SymmetricAlgorithm RC2 { get { return new RC2CryptoServiceProvider(); } }
- }
in order to export the CryptoComposer's properties you should use the following code:
Code Snippet
- var picker = new RegistrationBuilder();
- picker.ForType<CryptoComposer>()
- .ExportProperties(p => p.PropertyType == typeof(SymmetricAlgorithm));
-
- var catalog = new AssemblyCatalog(typeof(Program).Assembly, picker);
- var container = new CompositionContainer(catalog);
-
- var foo = container.GetExportedValue<Foo>();
summary
exporting properties using the fluent API is fairly straightforward.