文章出處

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


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()