Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are MEF exports cached or discovering every time on request?

Tags:

c#

.net

wpf

mef

If I have one type MyClass, register with

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

[PartCreationPolicy(CreationPolicy.Shared)]

or

[PartCreationPolicy(CreationPolicy.NonShared)]

and later trying to call

compositionContainer.GetExportedValue<Myclass>() multiple times.

Question: with the first call, I will get my registered class via MEF - llokup all registered assemblies, then trying to find one registered contract. Question is about second time and so on - will MEF do global lookup again or it caches somewhere internally?

like image 418
Lonli-Lokli Avatar asked Jan 11 '13 08:01

Lonli-Lokli


1 Answers

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<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) 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.

like image 91
Dennis Avatar answered Sep 20 '22 05:09

Dennis