C#MEF初步介绍

首先新建一个控制台工程.并添加MEF框架的引用,既 System.ComponentModel.Composition.dll,然后键入如下代码:


using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
using System;

public class Program
{
/// <summary>
/// Import表明要进行导入,遵守IMessageSender协定
/// </summary>
    [Import(typeof(IMessageSender))]
public IMessageSender MessageSender { get; set; }

public static void Main(string[] args)
    {
        Program p = new Program();
        p.Run();
    }

public void Run()
    {
//AggregateCatalog用来合并多个catalog
        var catalog = new AggregateCatalog();

///使用当前程序集构造AssemblyCatalog,并添加
///AssemblyCatalog对于
        AssemblyCatalog assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        catalog.Catalogs.Add(assemblyCatalog);

///如果还有其他要添加catalog可以继续添加,
///下面注释的2行代码表明,加载当前应用程序下Extensions中的程序集
        //string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Extensions");       
//catalog.Catalogs.Add(new DirectoryCatalog(path));

///初始化CompositionContainer
        var container = new CompositionContainer(catalog);

///从特性化对象的数组创建可组合部件,并在指定的组合容器中组合这些部件
///建立MEF包含CompositionContainer的实例,给它增加Composable part(包含程序自己本身)
///这是CompositionContainer对象的扩展方法
///方法原型:public static void ComposeParts(this CompositionContainer container, params object[] attributedParts);
///要在其中执行组合的组合容器
///要组合的特性化对象的数组
        container.ComposeParts(this);
        MessageSender.Send("Message Sent");
    }
}

/// <summary>
/// 定制导入协定
/// </summary>
public interface IMessageSender
{
void Send(string message);
}

/// <summary>
/// Export表明这是一个要导出的类,遵守IMessageSender协定
/// </summary>
[Export(typeof(IMessageSender))]
public class EmailSender : IMessageSender
{
public void Send(string message)
    {
        Console.WriteLine(message);
    }
}

 

你可能感兴趣的