MEF声明导入

声明导入
以下内容从http://mef.codeplex.com/摘抄而来

属性导入
用Import标示部件作为属性导入
class Program
  {
    [Import]
    public IMessageSender MessageSender { get; set; }
  }


构造器参数导入
通过将部件作为构造参数来实现导入
使用方法:
 1、添加ImportingConstructor属性
 2、为导入添加构造参数
class Program
  {
    [ImportingConstructor]
    public Program(IMessageSender messageSender)
    {
       ...
    }
  }

参数导入
class Program
  {
    [ImportingConstructor]
    public Program(IMessageSender messageSender)
    {
    }
  }

字段导入
  class Program
  {
    [Import]
    private IMessageSender _messageSender;
  }

随意导入
[Export]
public class OrderController {
  private ILogger _logger;

  [ImportingConstructor]
  public OrderController([Import(AllowDefault=true)] ILogger logger) {
    if(logger == null)
      logger = new DefaultLogger();
    _logger = logger;
  }
}

集合导入
使用 ImportMany 属性
public class Notifier
 {
    [ImportMany(AllowRecomposition=true)]
    public IEnumerable<IMessageSender> Senders {get; set;}

    public void Notify(string message)
    {
      foreach(IMessageSender sender in Senders)
      {
        sender.Send(message);
      }
    }
  }

IPartImportsSatisfiedNotification
public class Program : IPartImportsSatisfiedNotification
 {
    [ImportMany]
    public IEnumerable<IMessageSender> Senders {get; set;}

    public void OnImportsSatisfied()
    {
      // when this is called, all imports that could be satisfied have been

satisfied.
    }
  }

 

posted @ 2010-11-10 00:12  星空有我  阅读(472)  评论(0编辑  收藏  举报