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

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

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

Root partInstance = container.GetExportedValue<Root>();

 

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

 

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

 

GetExportedValueOrDefault
 
GetExportedValueOrDefault 和 GetExportedValue 的区别在于 GetExportedValueOrDefault 在没有任何匹配的状况下并不会抛出异常。
 
    var root = container.GetExportedValueOrDefault<Root>(); // may return null
 
原文地址:
相关文章
相关标签/搜索