MEF framework learning Tour (4) import and export (I)

Source: Internet
Author: User

The use of export and import in MEF is essentially the process of instantiating an object. Through the features of MEF, the direct dependency of the object is reduced, this allows the system design to achieve a highly flexible and scalable effect.

(This article is from msdn)

Import Type

MEF supports multiple import types, including dynamic import, delayed import, mandatory import, and optional import.

Dynamic Import

In some cases, the import class may need to match any type of export with a specific protocol name. In this case, the class can declare dynamic import. The following import matches any export with the protocol name "thestring.

Code segment

public class MyClass{    [Import("TheString")]    public dynamic MyAddin { get; set; }}

If the protocol type is inferred from the dynamic keyword, it will match any protocol type. In this case, the import shouldAlwaysSpecify the name of the protocol to be matched based on. (If the protocol name is not specified, the import is considered as not matching the export .) The following two exports match the previous import.

Code segment

[Export("TheString", typeof(IMyAddin))]public class MyLogger : IMyAddin { } [Export("TheString")]public class MyToolbar { }

Obviously, the import class must be prepared to process any type of objects.

Delayed Import

In specific design and development, some objects do not need to be instantiated during system running or affiliated object initialization, it is instantiated only when it is needed. In terms of the system, this is also a feasible way to improve the system performance, this method can be understood as the delayed initialization of an object, or delayed loading. In this case, the class can declare delayed import by using the protocol type lazy <t>. The following import attribute declares a delayed import.

Code segment

public class MyClass{    [Import]    public Lazy<IMyAddin> MyAddin { get; set; }}

From the perspective of the combination engine, the protocol type lazy <t> is considered to be the same as the protocol type T. Therefore, the previous import will match the following export.

Code segment

[Export(typeof(IMyAddin))]public class MyLogger : IMyAddin { }

You can specify the protocol name and protocol type for delayed import in the import feature.

 Required Import

The exported MEF parts are generally created by the composite engine to respond to the direct requests or requirements for matching imports. By default, the composite engine uses a constructor without parameters when creating a part. To enable the engine to use other constructors, you can mark it with the importingconstructor feature.

Each component may have only one constructor for the combined engine. If the default constructor and importingconstructor features are not provided, or multiple importingconstructor features are provided, errors will occur.

To populate the parameters of the constructor marked with the importingconstructor feature, all these parameters are automatically declared as import. This allows you to easily declare the import used during the part initialization process. The following classes use importingconstructor to declare the import.

Code segment

public class MyClass{    private IMyAddin _theAddin;     //Default constructor will NOT be    //used because the ImportingConstructor    //attribute is present.    public MyClass() { }     //This constructor will be used.    //An import with contract type IMyAddin is    //declared automatically.    [ImportingConstructor]    public MyClass(IMyAddin MyAddin)    {        _theAddin = MyAddin;    }}

 

By default, the importingconstructor feature imports all parameters using the inferred protocol type and protocol name. You can override this behavior by modifying parameters with the import feature, which can then explicitly define the protocol type and protocol name. The following code demonstrates a constructor that uses this syntax to import a derived class (instead of a parent class.

Code segment

[ImportingConstructor]public MyClass([Import(typeof(IMySubAddin))]IMyAddin MyAddin){     _theAddin = MyAddin;}

Be careful when using set parameters. For example, if you use a parameter of the ienumerable <int> type to specify importingconstructor on the constructor, the import will match a single export (instead of an import group with the int type) of ienumerable <int>. To match a set of exports of the int type, you must use the importmany feature to modify the parameter.

The parameters declared as imported by importingconstructor are also marked as required for import. MEF usually allows export and import to form a loop. For example, loop refers to object a importing object B, which in turn imports object. In general, loops do not become a problem, and the combined container constructs two objects normally.

When the constructor of a part needs to import the value, this object cannot participate in the loop. If object A requires that object B be constructed before it can be constructed and object B is imported to object A, the loop cannot be solved and a combination error occurs. Therefore, the import declared on the constructor parameters is a required import. You must satisfy these imports before using any export of the imported objects.

Optional

The import feature specifies the requirements for the normal running of parts. If the Import fails, the component combination fails and the component is unavailable.

You can use the allowdefault attribute to specify that the import is optional. In this case, the combination is successful even if the import does not match any available export, and the import property is set to the default value of its property type default (t) (For the object property isNullFor Boolean valuesFalse, The value attribute is zero .) The following classes use optional import.

Code segment

public class MyClass{    [Import(AllowDefault = true)]    public Plugin thePlugin { get; set; }    //If no matching export is avaliable,    //thePlugin will be set to null.}

The following is an example of an import parameter:

Code segment

 

   [Export]    public class OrderController    {        private ILogger _logger;        [ImportingConstructor]        public OrderController([Import(AllowDefault = true)] ILogger logger)        {            if (logger == null)                logger = new DefaultLogger();            _logger = logger;        }    }

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.