开发者

MEF Lazy ImportMany with Creationpolicy.NonShared

开发者 https://www.devze.com 2023-01-06 15:34 出处:网络
i\'m a beginner in mef and so i have a question :) i have the following: [PartCreationPolicy(CreationPolicy.Shared)]

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 Disp开发者_如何学Pythonlayname
    {
        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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消