MEF懒惰导入很多具有Creationpolicy.NonShared [英] MEF Lazy ImportMany with Creationpolicy.NonShared
问题描述
我是MEF的初学者,所以我有一个问题:) 我有以下内容:
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
}
现在我的问题是:执行Open()时,不应该总是创建一个新的NonShared1实例吗?我总是一样.
now my question: when Open() execute, shouldn't there always a new NonShared1 instance be created? i got always the same.
推荐答案
Matthew关于Shared/NonShared方面是正确的,它仅影响每次导入时给定的实例,每次拉Lazy.Value都不会获得新实例. .如果您想每次获取一个新实例并进行处理,则可以使用ExportFactory.当前,ExportFactory仅存在于MEF的Silverlight版本中,但是如果确实需要此功能,则mef.codeplex.com上有一个示例项目,该功能将该功能添加到了MEF的桌面版本中.
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.
这篇关于MEF懒惰导入很多具有Creationpolicy.NonShared的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!