. NET comes with IOC container MEF experience (GO)

Source: Internet
Author: User
Tags hosting

This article mainly explains MEF as an IOC container, and there are very many IOC containers available in. NET, such as Castlewindsor,unity,autofac,objectbuilder,structuremap, Spring.net, these third-party tools are different, but the function is generally the same, most need to pre-match interface and implementation (through code or configuration file), and then by the system automatically or manually through the interface to obtain an instance of the corresponding implementation class, the work of object instantiation is automatically completed by the IOC container.

Overview

Official saying: The Managed Extensibility Framework (MEF) is an extensibility management framework under the. NET platform, which is a collection of features, including dependency injection (DI). MEF provides developers with a tool that allows us to easily scale applications and minimize the impact of existing code, and developers define some extensibility points based on functional requirements in the development process, and the extension can then use these extension points to interact with the application At the same time, MEF has no direct dependency between the application and the Extender, which also allows the extension to be shared among multiple, equally extended requirements.

the problem solved

What does the MEF solve? In the past, if an application needed to support plug-ins the way it had to implement its own underlying and those plugins were typically specific to the application and could not be used by other applications. In fact, MEF provides the ability to discover and combine to enable your application to load extensions, providing a simple workaround for Runtime Extensibility: MEF provides a standard way for host applications to expose themselves and use external extensions. And the extension itself can be used by different applications. An extension can still be implemented using a method specific to the application. Dependencies can also exist between extensions, and MEF automatically calls them in the correct order. MEF also provides some methods for locating and loading the available extensions. MEF allows extensions to be tagged with additional metadata for easy, rich query and filtering purposes.

Working principle

Briefly speaking about how MEF works, the core of MEF consists of a catalog and a compositioncontainer. The category is used to discover extensions, and container is used to coordinate the creation and grooming of dependencies. Each composable part provides one or more export, and typically relies on one or more externally provided services or imports. Each part manages an instance to run for the application

MEF provides a way to discover components implicitly by "combining". A MEF component (called a "part-part"). A part declaratively specifies its dependencies (called "Import-import") together with its provided functionality (known as "Export-export"). The MEF principle is simple, to find a common interface of the import, export. Then find an instantiation of the export and assign it to the import. Ultimately, the MEF is finding the right class instantiation and handing it over to the import.

How to declare a part - Import and Export

Export is a value provided by the part to other parts in the container, and import is the requirement that the part presents to the container to be satisfied by the available exports. In the Attributed programming model, imports and exports are declared by a decorated class or member using the Import and export attributes. The Export attribute modifies a class, field, property, or method, and the Import attribute can decorate a field, property, or constructor parameter. In order for the import to match the export, the import and export must have the same contract.

Suppose there is a class MyClass, which declares that the type of plug-in that can be imported is IMyAddin.

Class myclass{    [Import]    set;}}  

Here is a class that declares to be exported. The same type is IMyAddin.

[Export (typeof(IMyAddin))]class Mylogger:imyaddin {}  

This allows us to obtain an instance of MyLogger when we use the MyAddIn property.

Found parts

MEF provides three ways to discover parts

    • Assemblycatalog the part is found in the current assembly.
    • Directorycatalog discovers the part in the specified directory.
    • Deploymentcatalog discovery of parts in the specified XAP file (for Silverlight)

When parts are discovered in different ways, Aggregatecatalog can also be used to aggregate these parts together.

New Aggregatecatalog ();            // Add the parts found in the program's assembly to the catalog            . Catalogs.add (new Assemblycatalog (typeof//) adds a part found from the specified path to catalog. Catalogs.add (new Directorycatalog ("c:\\users\\v-rizhou\\simplecalculator\\extensions"));  

How do I assemble parts?

After the parts have been loaded, place them in a compositioncontainer container.

New Compositioncontainer (catalog)

By calling the container's Composeparts () method, you can combine the parts in the container.

Container.composeparts (this);

Here we use a simple sample to learn to use MEF

1. Project Structure diagram

Note: Three items are added to the System.ComponetModel.Composition.dll reference.

2. mettest Project

(1) , IHelloWord.cs

The interface defined for us, there are only two simple methods, the code is as follows

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;  Namespaceinterfacestring SayHello (stringstring Sayword (string str);   } 

(2) HelloWord.cs

The file inherits the Ihelloword interface and implements the methods in the interface, the Helloword class is declared as internal to prevent the method from being referenced outside the class, declaring the class as an export with [Export (typeof (Ihelloword))] adornments, Type is Ihelloword and the code is as follows

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.ComponentModel.Composition;Namespace mettest{[Export (typeof internal classpublic string SayHello (string Str) {return hello "+ str;} public string Sayword ( String Str) {return str ; } }} 

(3) HelloWordB.cs

The file does not have to look at first, the following is used in the instructions

3. METTest1 first, the following is used in the instructions

4. mefconsoleapplication

The project is a console project, add a reference to the mettest, and do not add a reference to the METTest1 project.

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.ComponentModel.Composition;UsingMettest;UsingSystem.Reflection;UsingSystem.ComponentModel.Composition.Hosting;UsingSystem.IO;Namespacemefconsoleapplication{[Export]Classprogram {[Import]Public Ihelloword Helloword {GetSet; }Staticvoid Main (String[] args) {Program P =NewProgram (); P.method (); }PublicvoidMethod () {Aggregatecatalog catelog =NewAggregatecatalog (); Catelog. Catalogs.add (New Directorycatalog (Directory.GetCurrentDirectory ()));//Find parts, current application//Catelog. Catalogs.add (New Directorycatalog (@ "). /.. /.. /meftest1/bin/debug "));//We'll find the parts through the path.//Catelog. Catalogs.add (New Assemblycatalog (assembly.getexecutingassembly ())); Compositioncontainer container =New Compositioncontainer (Catelog);//DECLARE Container container.composeparts (this);//Assemble the parts of the container together//compositionbatch Batch = new CompositionBatch (); Span style= "color: #008000;" >//batch.addpart (this); //container.compose (Batch); //helloword = container. Getexportedvalue<ihelloword> (); // This can also be instantiated as an excuse Console.WriteLine (Helloword.sayhello ( Span style= "color: #800000;" > "eric ); Console.WriteLine (Helloword.sayword ( "_eric " 

Operation Result:

5. Let's take a look at an interface that is instantiated by multiple classes

When an interface is instantiated by more than one class, it is declared with ImportMany, as follows

[ImportMany]   set;}

Open the HelloWordB.cs file to inherit the Ihelloword and decorate it with [Export (typeof (Ihelloword))]. In this way Helloword and Hellowordb both inherit Ihelloword and declare with [Export].

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.ComponentModel.Composition;Namespacemettest{[Export (typeofinternal classpublic string SayHello (string Str) {return  I am hellob: "+ str;} public string Sayword ( String Str) {return b_ "+STR;}}       
View Code

Modify The Program.cs of the Mefconsoleapplication project

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;UsingSystem.Text;UsingSystem.ComponentModel.Composition;UsingMettest;UsingSystem.Reflection;UsingSystem.ComponentModel.Composition.Hosting;UsingSystem.IO;Namespacemefconsoleapplication{[Export]Classprogram {[ImportMany]Public ienumerable<ihelloword> Helloword {GetSet; }Staticvoid Main (String[] args) {Program P =NewProgram (); P.method (); }PublicvoidMethod () {Aggregatecatalog catelog =NewAggregatecatalog (); Catelog. Catalogs.add (New Directorycatalog (Directory.GetCurrentDirectory ()));//Find parts, current application//Catelog. Catalogs.add (New Directorycatalog (@ "). /.. /.. /meftest1/bin/debug "));//We'll find the parts through the path.//Catelog. Catalogs.add (New Assemblycatalog (assembly.getexecutingassembly ())); Compositioncontainer container =New Compositioncontainer (Catelog);//DECLARE Container container.composeparts (this);//Assemble the parts of the container together//CompositionBatch Batch = new CompositionBatch ();//Batch.addpart (this);//container.compose (Batch); //helloword = container. Getexportedvalue<ihelloword> (); // This can also be instantiated as an excuse //console.writeline (Helloword.sayhello ("Eric")); //console.writeline (Helloword.sayword ("_eric")); Span style= "color: #0000ff;" >foreach (var item in Helloword) {Console.WriteLine (item. SayHello ( "eric" )); } console.read (); } }} 
View Code

This article refers to:

Http://wenku.baidu.com/view/abc72ec80508763231121273.html

Http://www.cnblogs.com/techborther/archive/2012/02/06/2339877.html

Click to download source code

Learn a little every day and make a little progress every day.

. NET comes with IOC container MEF experience (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.