您的位置:首页 > 博客中心 > 互联网 >

MEF 编程指南(十一):查询 CompositionContainer

时间:2022-04-20 21:19

CompositionContainer 公开了一部分获取导出、导出对象以及两者集合的重载。

  在这些方法重载中,你应该遵循下面的共享行为准则 - 除非特别说明。  
  • 当请求单一实例的时候,如果没发现任何导入,将会抛出异常。
  • 当请求单一实例的时候,如果发现不止一个导入,将会抛出异常。
  GetExportedValue   在下面的代码片段里,我们请求 Root(契约)实例的实例。  
var container = new CompositionContainer(new AssemblyCatalog(typeof(Program).Assembly));

Root partInstance = container.GetExportedValue();

 

如果有一个不同合同名称的导出,你需要使用一个不同的重载:  
[Export("my_contract_name")]
public class Root
{
}
var container = new CompositionContainer(new AssemblyCatalog(typeof(Program).Assembly));
Root partInstance = container.GetExportedValue("my_contract_name");

 

GetExport   GetExport 检索延迟引用实例化导出。访问导出的 Value 属性将会迫使导出实例的创建。多次调用导出的 Value 属性只会返回同一实例,无论部件拥有 Shared 生命期还是 Non-Shared 生命期。  
Lazy export = container.GetExport();
var root = export.Value; //create the instance.

 

GetExportedValueOrDefault   GetExportedValueOrDefault 和 GetExportedValue 的区别在于 GetExportedValueOrDefault 在没有任何匹配的情况下并不会抛出异常。  
    var root = container.GetExportedValueOrDefault(); // may return null
  原文地址: http://mef.codeplex.com/wikipage?title=Querying%20the%20Composition%20Container&referringTitle=Guide

 

 

MEF 编程指南(十一):查询 CompositionContainer,布布扣,bubuko.com

本类排行

今日推荐

热门手游