原来写插件还可以选MEF

MEF是微软提供的一个轻量级的ICO容器,可以轻易的解除程序集的依赖关系,最近想写个类似插件试的软件所以搜索了一下,终于淘到宝了。

 

下面我们看看MEF是如何解耦的

 

新建一个控制台项目两个类库

 

 

Itest中添加接口文件Istudent

 

namespace ITest

{

    public interface   IStudent

    {

         string Say(string msg);

    }

}

 

Test中添加引用

 

 

 

添加Student类文件;

 

using ITest;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.ComponentModel.Composition;//添加引用

namespace Test

{

     [Export(typeof(IStudent))]//用于输出类行

    public class Student:IStudent

    {

        public string Say(string msg)

        {

            return "你好:" + msg;

        }

    }

}

 

 

控制台程序中也添加引用

注意只添加了接口类库的引用,并没有添加Test类库的引用;

 

 

 

编写主函数:

 

using ITest;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.ComponentModel.Composition;

using System.ComponentModel.Composition.Hosting;

using System.IO;

 

namespace MEF

{

    class Program

    {

        [Import]//MEF导入特性标签,用于实例化;

        public IStudent student { get; set; }

        static void Main(string[] args)

        {

            Program p = new Program();

            p.Deal();

        }

 

        public void Deal()

        {

            AggregateCatalog catelog = new AggregateCatalog();

 

            catelog.Catalogs.Add(new DirectoryCatalog("..\\..\\..\\Test\\bin\\Debug"));//根据相对路径去找对象;

 

            CompositionContainer container = new CompositionContainer(catelog);//声明容器

 

            container.ComposeParts(this);//把容器中的部件组合到一起

 

            Console.WriteLine(student.Say("干嘛去?"));

            Console.Read();

        }

    }

}

 

 

 

 

 

总结:

 

MEF自动将  [Export(typeof(IStudent))]和[Import]指定的两个对象进行绑定,帮助我们完成实例化;

 

MEF实例化对象只需要四部,

  1. 创建合并对象目录AggregateCatalog实例
  2. 根据地址添加目录到对象中;
  3. 创建容器对象,
  4. 绑定导入和导出的对象,完成实例化;

 

参考文档:

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

posted @ 2016-10-22 01:41  圣叹&北京  阅读(162)  评论(0编辑  收藏  举报