A composite part is a combination unit of MEF. A composite part can provide export services for other parts, or import services for other parts. A component contains at least one export. In MEF, the Export and Import features are used to indicate Export and Import. parts can be directly added to the combined container or the directory can be added to the combined container, the default directory is identified by export.
There is no dependency between parts, but all parts depend on the contract. By default, type contract should be used instead of string contract. String contract can easily cause fuzzy match. If necessary, you can add company names, namespaces, and other prefixes.
You can use a fixed class for the exported contract, but usually use interfaces and abstract classes. This makes it easy to import multiple different classes at a time. The following example shows this advantage.
Note: In this case, each export must mark a specific interface type. Otherwise, the type itself is exported.
Example:
Using system; using system. componentmodel. composition; using system. componentmodel. composition. hosting; using system. collections. generic; namespace contractconsole {// <summary> /// host // </Summary> class program {/// <summary> /// import a specific export set /// </Summary> [importtasks] public ienumerable <iwaiter> waiters {Get; set;} static void main (string [] ARGs) {program P = new program (); p. run ();} // <summar Y> // test Import /// </Summary> Public void run () {compent (); Policy (""); console. read () ;}/// <summary> /// composite container /// </Summary> private void compent () {var catalog = new assemblycatalog (system. reflection. assembly. getexecutingassembly (); var Container = new compositioncontainer (Catalog); container. composeparts (this );} /// <summary> /// call the method of the imported object /// </Summary> /// <Param name = "name"> </param> pub LIC void Policy (string name) {foreach (iwaiter waiter in waiters) {waiter. hellow (); waiter. service (name); waiter. goodbye (); console. writeline () ;}}/// <summary >/// interface //</Summary> Public interface iwaiter {void hellow (); void Service (string name ); void goodbye () ;}/// <summary> /// export the restaurant class /// </Summary> [Export (typeof (iwaiter)] public class diningroomwaiter: iwaiter {public void hello W () {console. writeline ("welcome to the old man! ");} Public void Service (string name) {console. writeline! ----------- "+ Name);} public void goodbye () {console. writeline (" welcome to the next visit! ") ;}/// <Summary> // export the bar class /// </Summary> [Export (typeof (iwaiter)] public class barwaiter: iwaiter {public void hellow () {console. writeline ("welcome to the cool bar! ");} Public void Service (string name) {console. writeline (" excuse me, please try it slowly! ----------- "+ Name);} public void goodbye () {console. writeline (" welcome to the next visit! ");}}}
Execution result: