是否每次都要求MEF导出缓存或发现?

Lon*_*kli 6 .net c# wpf mef

如果我有一个类型MyClass,请注册

[Export(typeof(Myclass))] 属性,和

[PartCreationPolicy(CreationPolicy.Shared)]

要么

[PartCreationPolicy(CreationPolicy.NonShared)]

然后试着打电话

compositionContainer.GetExportedValue<Myclass>() 多次.

问题:通过第一次通话,我将通过MEF获取我的注册课程 - llokup所有已注册的程序集,然后尝试查找一个已注册的合同.问题是关于第二次等等 - MEF会再次进行全局查询还是在内部缓存?

Den*_*nis 7

MEF会再次进行全局查找,还是在内部缓存

是的,如果您对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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

当然,在使用CreationPolicy.NonShared时,当您请求时,导出的值会一次又一次地创建.但即使在这种情况下,也不会执行"全局查找",因为无论如何都要缓存元数据.