首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

MEF 程式設計指南(一):應用程式中托管 MEF 入門

     編輯:關於.NET

托管 MEF 核心步驟:建立 CompositionContainer、載入目錄、呼叫 ComposeParts。首先參考 System.ComponentModel.Composition.dll。

最小托管程式碼

private void Compose()
{
    var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
    var container = new CompositionContainer(catalog);
    container.ComposeParts(this);
}

完整導入/導出範例

定義介面與實作,實作標記 [Export]:

public interface IBookService
{
    void GetBookName();
}

[Export(typeof(IBookService))]
public class ComputerBookService : IBookService
{
    public void GetBookName() => Console.WriteLine("《Hello Silverlight》");
}

宿主類別定義導入屬性:

class Program
{
    [Import]
    public IBookService Service { get; set; }

    private void Compose()
    {
        var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this, new ComputerBookService());
    }

    static void Main(string[] args)
    {
        var p = new Program();
        p.Compose();
        p.Service.GetBookName(); // 輸出書名
    }
}

此範例展示 MEF 最基礎的「目錄 → 容器 → 組合」流程,也是所有進階應用的基石。參考資料:Hosting MEF in an application,官網 mef.codeplex.com。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved