MEF 2.0 – mini series: part 2 (Fluent and Conventional Export)

2013/01/06

MEF 2.0 – mini series: part 2 (Fluent and Conventional Export)

this is the second post in the MEF 2.0 mini series.
you can see the following TOC for more.

in this post I will start to cover the fluent discovery model and the idea of discovery by convention.

MEF, Import, Export, CompositionContainer, RegistrationBuilder, Catalog

traditionally, out of the box, MEF come with a single discovery model, which was the Attribute model.

it is true that you could extend MEF’s discovery model by using either a custom catalog or a custom export provider, but this task wasn’t as simple as the MEF 2 fluent discovery model and therefore wasn’t a common practice.

Registration Builder

MEF 2.0 is  having the new RegistrationBuilder class which can be used to apply a custom picker (filter) for specific types within the scope of a catalog.

the idea is that the catalog will apply a sandbox which is a searching area scope (like Assembly, Directory, ext…), while the registration builder will pick up the relevant exported part within the scope.

actually the catalog will compose both the old attribute model and the picked up types.

this technique can be used either as a replacement for the Attribute model or as a complementary for 3rd party types which we cannot recompile with the [Export] attribute.

in order to work with the registration builder, you should add reference to

  • System.Reflection.Context
  • System.ComponentModel.Composition
  • System.ComponentModel.Composition.Registration

at its simplest form it can be used to append a specific type into the composition.

Code Snippet
  1. static void Main(string[] args)
  2. {
  3.     Program p = new Program();
  4.  
  5.     var picker = new RegistrationBuilder();
  6.     picker.ForType<AesManaged>()
  7.         .Export<SymmetricAlgorithm>();
  8.  
  9.     var catalog = new TypeCatalog(
  10.         new []{typeof(AesManaged)}, picker);
  11.  
  12.     var container = new CompositionContainer(catalog);
  13.     container.ComposeParts(p);
  14. }
  15.  
  16. [Import]
  17. private SymmetricAlgorithm Crypto { get; set; }

the above code exporting the AesManaged cryptography algorithm as a symmetric crypto algorithm.

currently the Import is still using the old Attribute model. I will show you how to define a fluent Imports in future post.

another aspect that you can control is the instantiation strategy by using the SetCreationPolicy:

Code Snippet
  1. var picker = new RegistrationBuilder();
  2. picker.ForType<AesManaged>()
  3.     .Export<SymmetricAlgorithm>()
  4.     .SetCreationPolicy(CreationPolicy.NonShared);

in future post I will talk about creation scope and lifetime, which is a fine tuning option for the part lifetime control.

Export inheritance

you can choose to export anything that derived from a Type or implement an Interface:

Code Snippet
  1. picker.ForTypesDerivedFrom<SymmetricAlgorithm>()
  2.     .Export<SymmetricAlgorithm>()
  3.     .SetCreationPolicy(CreationPolicy.NonShared);

Export by conventions

a common IoC strategy is to discover extensions by convention.
for example loading all the type with a ‘Plugin’ suffix.
this strategy reduce the maintenance of either xml files or bootstrapper code.

this type of discovery made easy in MEF 2.0.

the following code is loading any type which is ending with a ‘Plugin’ extension into the composition.

Code Snippet
  1. picker.ForTypesMatching(pl => pl.Name.EndsWith("Plugin"))
  2.     .ExportInterfaces();

as you can see that the code is exporting all of the interfaces that was implemented by the plugins.

foe example, if you are having the following interfaces and implementation:

Code Snippet
  1. public interface ILogPlugin
  2. {
  3.     void Write(string message);
  4. }
  5. public class LoggerPlugin : ILogPlugin
  6. {
  7.     public void Write(string message) { /* … */}
  8. }
  9.  
  10. public interface ISavePlugin
  11. {
  12.     void Save(string message);
  13. }
  14. public class FilePlugin : ISavePlugin
  15. {
  16.     public void Save(string message) { /* … */}
  17. }

LoggerPlugin will be export as ILogPlugin and FilePlugin will be export as ISavePlugin.

ExportInterfaces is having a few overloads which you can use to refine the interface exporting, instead of exporting all of the implemented interfaces, you can define a convention, for example:

Code Snippet
  1. picker.ForTypesMatching(pl => pl.Name.EndsWith("Plugin"))
  2.     .ExportInterfaces(t => t.Name.EndsWith("Plugin"));

Summary

MEF 2.0 fluent and conventional model is a great improvement over the Attribute model. as you can see you can use both model together, but the convention model can ease your maintenance.

in the next post I will discuss it further.

Shout it

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

12 comments

  1. Celine Party Handbag2013/11/18 ב 19:17

    We imagine you are pleased and sending lots of love!

    Reply
  2. miu miu shop ruger2013/11/21 ב 12:52

    One of the latest new additions is the Miu Miu woven fringe hobo. The hobo is dressed in a woven pattern body and features double trails of fringe down each side.

    Reply
  3. Cheap Furla Sale2013/11/30 ב 22:06

    Generally I do not read post on blogs, however I wish to say that this write-up very pressured me to take a look at and do it! Your writing style has been amazed me. Thank you, quite nice post.

    Reply
  4. gamma blue 11s2013/12/01 ב 22:25

    Altruiste vendeur, gamma blue 11s conforme, qualité, concentration et colis rapide

    Reply
  5. http://www.rotisserieportugalia.ca/uggs-australia-in-grey-c-252013/12/05 ב 06:35

    I have realized that online education is getting favorite because getting your degree online has developed into popular method for many people.http://www.angionet.ch Quite a few people have not necessarily had a chance to attend a conventional college or university yet seek the elevated earning possibilities and career advancement that a Bachelors Degree gives you. Still other folks might have a diploma in one field but would choose to pursue some thing they now possess an interest in.

    Reply
  6. cheap uggs online2013/12/07 ב 00:56

    A wonderful story. Thank you!

    Reply
  7. Louis Vuitton new products2013/12/14 ב 19:13

    Thanks for the strategies you are discussing on this blog. Another thing I’d really like to say is the fact http://www.louisvuittonstore.us getting hold of duplicates of your credit file in order to scrutinize accuracy of each detail is the http://www.louisvuittonstore.us first motion you have to perform in repairing credit. You are looking to freshen your credit profile from detrimental details problems that spoil your credit score.

    Reply
  8. サッカーショップ2013/12/15 ב 19:58

    collocation with coriaceous glove more typically the nature this visibility feels attracting. Classy wave Fordi Renlei breaths over elegant popular Fordi Renlei your glove which will Ha Na purposes products you can a material which work equal of any part and coloring can

    Reply
  9. http://www.wrr.fr/site_map.html2013/12/16 ב 17:58

    These days of austerity and relative stress and anxiety about running into debt, most people balk about the idea of employing a credit card in order to make purchase of merchandise or pay for a vacation, preferring, instead to rely on a tried in addition to trusted means of making repayment – cash. However, in case you have the cash on hand to make the purchase completely,http://www.webpower.fr then, paradoxically, that’s the best time for them to use the card for several good reasons.

    Reply
  10. asics soldes2013/12/21 ב 19:18

    It is my belief that mesothelioma will be the most fatal cancer. It’s got unusual traits. The more I look at it a lot more I am assured it does not work like a real solid flesh cancer. In the event mesothelioma is actually a rogue viral infection, so there is the possibility of developing a vaccine and also offering vaccination to asbestos exposed people who are at high risk of developing upcoming asbestos connected malignancies. Thanks for giving your ideas on this important ailment.

    Reply
  11. new bingo sites2013/12/23 ב 01:38

    I every t&X69;me sρent mу half an hour to read this websіte’ѕ content
    everyday al&X6f;ng ωith a cuρ of cοffee.

    Reply
  12. dor cohen2016/08/22 ב 03:09

    Wow, superb blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is excellent, let alone the content!

    Reply