MEF is easy to get started with, but it strives to be easy to understand (5 ).
We have successfully achieved the goal, greatly reducing the if else.
However, most of the articles in the garden use Import and ImportMany. So, modify the main function.
Using IPart; using System. collections. generic; using System. componentModel. composition; using System. componentModel. composition. hosting; using System. linq; namespace meftest {class Program {[importhandler] private IEnumerable <Lazy <IFileHandler, IPatMetadata> fileHandlers; // warning that no value has been assigned. Ignore this. MEF will import it by itself. Static void Main (string [] args) {// simulate data. String [] files = new string [] {@ "c: \ xxoo \ xxoo.txt", @ "c: \ xxoo \ ooxx.doc", @ "d: \ test directory \ mm.jpg ", @" e: \ movie \ Tian haiyi. avi ",}; Program p = new Program (); p. compose (); foreach (var file in files) {string ext = System. IO. path. getExtension (file ). toLower (); var export = p. fileHandlers. singleOrDefault (o => o. metadata. extension = ext); // locate the corresponding processing instance if (export! = Null) export. value. process (file);} Console. readLine ();} private void Compose () {// AssemblyCatalog directory, indicating searching var assemblyCatalog = new AssemblyCatalog (typeof (Program) in the Assembly ). assembly); // This sentence is actually useless, because this Assembly does not have any instances (various handler) We need. // you can search for the dll in a directory. Var directoryCatalog = new DirectoryCatalog (AppDomain. currentDomain. baseDirectory ,"*. dll "); var aggregateCatalog = new AggregateCatalog (assemblyCatalog, directoryCatalog); // The aggregation directory contains two search methods: var container = new CompositionContainer (aggregateCatalog); container. composeParts (this); // combines parts. This means to assemble all the parts of the Export into the attributes marked as Import and ImportMany in this instance. }}}
However, there is a point to note that it cannot be assembled within the main function. For example.
Running result:
OK, now you are getting started with MEF, and I think it's a bit difficult to read from my article. This series ends.