Search code examples
c#meflazy-evaluation

MEF Lazy ImportMany with Creationpolicy.NonShared


i'm a beginner in mef and so i have a question :) i have the following:

[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(SharedExport))]
public class SharedExport : INPCBase
{
    [ImportMany(typeof(INonShared),RequiredCreationPolicy = CreationPolicy.NonShared)]
    private IEnumerable<Lazy<INonShared,Dictionary<string,object>>> fac;

    ...

    public void Open()
    {
        foreach (var lazy in fac)
        {
            this.Muster.Add(lazy.Value);
        }

    }

the imported classes all marked as nonshared.

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(INonShared))]
[ExportMetadata("Muster","030")]
public sealed class NonShared1 : INPCBase, INonShared
{
    public NonShared1()
    {
        Debug.WriteLine("ctor NonShared1" + this.GetHashCode().ToString());
    }

    #region Implementation of INonShared

    public string Displayname
    {
        get { return "Muster 030 "+ this.GetHashCode().ToString(); 
        }
    }

    #endregion
}

now my question: when Open() execute, shouldn't there always a new NonShared1 instance be created? i got always the same.


Solution

  • Matthew is correct about the Shared/NonShared aspect only affecting the instance given at each import, you will not get a new instance every time you pull on Lazy.Value. If what you want is to get a new instance each time and dispose it you might look into using ExportFactory. Currently ExportFactory only exists in the Silverlight version of MEF but there is a sample project on mef.codeplex.com that adds the functionality to the desktop version of MEF if you really need this functionality.