Are MEF exports cached or discovering every time on request?

前端 未结 3 1375
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 16:23

If I have one type MyClass, register with

[Export(typeof(Myclass))] attribute, and

[PartCreationPolicy(CreationPolicy.Shared)]

3条回答
  •  醉话见心
    2021-01-05 16:46

    will MEF do global lookup again or it caches somewhere internally

    Yes, MEF perfoms some caching and widely uses lazy initialization, if you question is about MEF performance:

    1) metadata (composable parts, export definitions and import definitions) is cached. Example:

    public override IEnumerable ExportDefinitions
    {
        get
        {
            if (this._exports == null)
            {
                ExportDefinition[] exports = this._creationInfo.GetExports().ToArray();
                lock (this._lock)
                {
                    if (this._exports == null)
                    {
                        this._exports = exports;
                    }
                }
            }
            return this._exports;
        }
    }
    

    2) exported values are cached too:

    public object Value
    {
        get
        {
            if (this._exportedValue == Export._EmptyValue)
            {
                object exportedValueCore = this.GetExportedValueCore();
                Interlocked.CompareExchange(ref this._exportedValue, exportedValueCore, Export._EmptyValue);
            }
            return this._exportedValue;
        }
    }
    

    Of course, when using CreationPolicy.NonShared, exported value becomes created again and again, when you requesting it. But even in this case "global lookup" isn't performed, because metadata is cached anyway.

提交回复
热议问题