[. NET] talking about the extensibility framework: MEF

Source: Internet
Author: User

[. NET] talking about the extensibility framework: MEF

Previously, when using the Prism Framework, we were exposed to the scalability Framework MEF (Managed Extensibility Framework) and experienced the great convenience and scalability brought by MEF.

This article will compile an application that can be combined to help you quickly familiarize yourself with MEF and apply it to actual projects.

For the glossary and function implementation in MEF, please move to: train ticket

 

This section describes the Demo program () to be compiled and developed using winform.

Through the combination operation, the program dynamically loads available parts for the combination operation. By means of dismounting, the program uninstalls all the loaded parts.

After creating a project, you must reference the Assembly:

System.ComponentModel.Composition

The core code of the main program is as follows:

public partial class Form1 : Form, IPartImportsSatisfiedNotification  {        [ImportMany(AllowRecomposition = true)]        private IEnumerable
 
  > plugins;        private AggregateCatalog catalog;        private CompositionContainer container;        public Form1()        {            InitializeComponent();            if (catalog == null)                catalog = new AggregateCatalog();            this.container = new CompositionContainer(catalog);            this.container.ComposeParts(this);        }        #region Implementation of IPartImportsSatisfiedNotification        public void OnImportsSatisfied()        {            flowLayoutPanel1.Controls.Clear();            if (plugins != null && plugins.Count() != 0)            {                plugins.ToList().ForEach((a) =>                {                    Button btn = new Button();                    btn.Cursor = System.Windows.Forms.Cursors.Hand;                    btn.Width = 100;                    btn.Height = 50;                    btn.Text = a.Metadata.ThePluginName;                    btn.Click += (d, b) => { a.Value.Run(); };                    flowLayoutPanel1.Controls.Add(btn);                });            }        }        #endregion        public void CompositionAction()        {            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));        }        ......  }
 

1. IPartImportsSatisfiedNotification interface: Call OnImportsSatisfied after the component is imported ).

2. There are three common directories in MEF: AssemblyCatalog, DirectoryCatalog, and AggregateCatalog)

AssemblyCatalog.

var catalog = new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly());

Directory directory (DirectoryCatalog): Find the parts that can be imported from the folder

var catalog = new DirectoryCatalog(Extensions);

AggregateCatalog

var catalog =new AggregateCatalog(  new AssemblyCatalog(System.Reflection.Assembly.GetExecutingAssembly()),   new DirectoryCatalog(Extensions));

3. CompositionContainer: combines containers and manages components. It provides a series of extension methods for creating component instances.

4. General Usage of directories and containers:

var catalog =new AggregateCatalog();    var container =new CompositionContainer(catalog);    var container.ComposeParts(this);

5. Import: ImportAttribute and ImportManyAttribute

Used for the following purposes: field, attribute, Method

[import]private IData _data;[import]public IData Data{set;get;}[import]public Action ClickAction;

ImportManyAttribute)

[ImportMany]private IEnumerable
 
   plugins;
 

AllowRecomposition: whether to allow restructuring

AllowRecomposition = true: for example, when a program is running, adding an exported part to the aggregation directory dynamically can cause a reorganization operation.

catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));

Note that the DirectoryCatalog operation is not triggered. You can use the Refresh method to specify the reorganization policy.

6. System. Lazy : MEF provides delayed import.

Let's take a look at how plug-ins are implemented:

    [ExportPluginAttribute(typeof(IPlugin), ThePluginName = TheFristPlugin)]    public class TheFristPlugin : IPlugin    {        public TheFristPlugin()        {            this.TheName = TheFristPlugin;        }        #region Implementation of IPlugin        public string TheName { get; set; }        public void Run()        {            MessageBox.Show(TheFristPlugin);        }        #endregion    }

1. Briefly speaking: the relationship between import and export

A Scalable program developed based on MEF must have a lot of Export (exports) in the container, and how can these exports find their own destination.

The Export and Import depend on a contract to determine whether the other party is its own brother. To put it bluntly, it is an interface, such as the IPlugin interface defined by the above program.

public interface IPlugin    {        void Run();    }

Export using the ExportAttribute feature:

[Export(count)] public int count{ get{return 0;} } [Export(typeof(Action))] public void SendMsg(){return;}  [Export] public class Person{} 

The main program requires that the plug-in name be specified:

1. Define the Name field in the IPlugin Interface

2. Use metadata

3. Use the custom export feature (similar to the second solution)

How to use metadata?

1. Define the metadata view. The view uses the interface type here.

public interface IPluginMetadata {     string ThePluginName { get; } }

2. Use the ExportMetaData feature when exporting parts

[ExportMetadata(ThePluginName, TheFivePlugin)][Export(typeof(mef.test.wform.Interface.IPlugin))]public class TheFivePlugin : mef.test.wform.Interface.IPlugin{     public void Run()     {         MessageBox.Show(TheFivePlugin);     }}

3. Import metadata

 

        [ImportMany(AllowRecomposition = true)]private IEnumerable
 
  > plugins;
 

 

4. access metadata

 

Lazy
 
  .Value.Metadata
 

 

End

So far, the basic content of MEF has been explained. If there are any omissions, please leave a message to point out.

Many of the articles are in Vernacular and non-official languages. If there is anything wrong, I hope you can point out it.

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.