MEF is easy to get started with, but it strives to be easy to understand (3 ).
In the previous article, we have obtained instance types, but we still cannot effectively control them.
The ExportMetadata attribute can be used to mark a specific instance, which is equivalent to a name. I don't know whether to understand this.
Add an API IPatMetadata to the IPart Project
Namespace IPart {public interface IPatMetadata {string Extension {get;} // is distinguished by the suffix. Note that the name here must be consistent with that in ExportMetadata. }}
Add the specific export metadata ExportMetadata to the export location. Take txtFileHandler as an example.
Using IPart; using System. componentModel. composition; namespace Parts {[Export (typeof (IFileHandler)] // indicates that this class needs to be exported. The Export type is IFileHandler [ExportMetadata ("Extension ",". txt ")] // export metadata ext. the value is. txt public class TxtFileHandler: IFileHandler {public void Process () {Console. writeLine ("processing text files ");}}}
When metadata is added to the export, a slight change occurs during import and use.
Main function:
Using IPart; using System. ComponentModel. Composition. Hosting; namespace meftest {class Program {// container for installation. No matter what you install. Private static CompositionContainer container; static void Main (string [] args) {// AssemblyCatalog Directory, which indicates 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); // create a component and place it in the container. Container = new CompositionContainer (aggregateCatalog); var exports = container. getExports <IFileHandler, IPatMetadata> (); // obtain all exported parts (IFileHandler with IPatMetadata type metadata and the metadata name is Extension ). Foreach (var item in exports) {Console. WriteLine (item. Metadata. Extension); // Metadata can be obtained here
Item. Value. Process (); // IFileHandler. Process () can already be called here} Console. ReadLine ();}}}
Running result:
In this example, we can obtain all the file Handler and its corresponding metadata, in this way, we can obtain the corresponding instance of a specific file in the form of linq for processing. It is easy to say when you see the code.
Next, we will pass in the file name variable to create a complete file manager.
I hate a lot of articles in the world. Please do not repost them.