tags:

views:

360

answers:

2

hi, 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.

+1  A: 

No, because of the Lazy<> instance. A Lazy<T> is designed for lazy loading of a value. The value is created the first time you access the .Value property, and the same instance is returned for all access to that property thereafter. The NonShared/Shared creation policy comes into play doing the import process, so through property injection, constructor injection, field injection, .GetExportedValue etc...

Matthew Abbott
thanks. so CompositionContainer.ReleaseExport(lazy) didn't work either? all i want is to dispose the lazy instance :)
blindmeis
the crazy thing is, i got a second prototyp app with the mefedmvvm lib and there this works ... i got everytime a new instance. but i don't get the difference to my testapp:)
blindmeis
+3  A: 

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.

Wes Haggard
thx for the ExportFactory hint. i will give it a try :)
blindmeis
i tried the exportFactory for desktop version, but still has some problems. i've post the question at http://mef.codeplex.com/Thread/View.aspx?ThreadId=207539. maybe you have time to look at it? thx frank
blindmeis
got ExportFactory working now, thx a lot for this tip
blindmeis