c# - MEF 导出是否每次都根据请求进行缓存或发现?

标签 c# .net wpf mef

如果我有一种类型的 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/

相关文章:

c# - 定期读取从 Http PostAsync 返回的 Task<Stream> 响应内容

c# - 非托管到托管结构

c# - 使用 EasyNetQ.Hosepipe 时有没有办法指定不同的错误队列?

.net - 用于检查哪个机器人访问过的分析 API

c# - PreviewMouseLeftButtonDown 干扰点击选择

c# - 如何在不指定确切键的情况下读取用户按下的键?

c# - 为 ASP.NET Core 中的选项自定义 JSON 属性名称

c# - 由于 Dependent Role 属性不是关键属性,因此 Dependent Role 的重数上限必须为 '*'

wpf - 如何手动重新加载 WPF 的 Visual Studio 设计器

c# - WPF 自定义弹出窗口