如果我有一种类型的 MyClass,请注册
[Export(typeof(Myclass))]
属性,和
[PartCreationPolicy(CreationPolicy.Shared)]
或
[PartCreationPolicy(CreationPolicy.NonShared)]
然后尝试调用
compositionContainer.GetExportedValue<Myclass>()
多次。
问题:在第一次调用时,我将通过 MEF 获取我的注册类 - llokup 所有注册程序集,然后尝试查找一个注册契约(Contract)。问题是关于第二次等等 - MEF 会再次进行全局查找还是在内部某处缓存?
最佳答案
will MEF do global lookup again or it caches somewhere internally
是的,MEF 执行一些缓存并广泛使用惰性初始化,如果您对 MEF 性能有疑问:
1) 缓存元数据(可组合部分、导出定义和导入定义)。示例:
public override IEnumerable<ExportDefinition> ExportDefinitions
{
get
{
if (this._exports == null)
{
ExportDefinition[] exports = this._creationInfo.GetExports().ToArray<ExportDefinition>();
lock (this._lock)
{
if (this._exports == null)
{
this._exports = exports;
}
}
}
return this._exports;
}
}
2) 导出的值也被缓存:
public object Value
{
get
{
if (this._exportedValue == Export._EmptyValue)
{
object exportedValueCore = this.GetExportedValueCore();
Interlocked.CompareExchange(ref this._exportedValue, exportedValueCore, Export._EmptyValue);
}
return this._exportedValue;
}
}
当然,当使用 CreationPolicy.NonShared
时,导出的值会在您请求时一次又一次地创建。但即使在这种情况下也不会执行“全局查找”,因为无论如何都会缓存元数据。
关于c# - MEF 导出是否每次都根据请求进行缓存或发现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14274475/