MEF:如何检索类型的新实例?
在我的类中,我有一个类导入如下类型:
[Import]
public ContactViewModel ContactViewModel { get; set; }
该类型定义如下:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(ContactViewModel))]
public class ContactViewModel {}
我期望每当我从属性中读取时,都会获得一个新实例,对吧? 或者也许不是......我不断获得相同的实例,在使用该属性时如何强制为我创建一个新实例?
非常感谢,
Within my class I have a class that imports a type like this:
[Import]
public ContactViewModel ContactViewModel { get; set; }
The type is defined like this:
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(typeof(ContactViewModel))]
public class ContactViewModel {}
I am expecting whenever I would read from the property, to get a new instance right?
Or maybe not...I keep getting the same instance, how do I force t to make me a new instance when using the property?
Many Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您确定要重构您的消费者阶层吗?
NonShared
创建策略将确保每次需要组合该部分时都会创建一个新实例,因此我会检查它的另一面,即您所在的类[Import ]
-你的部分。该类是否被正确重构?您的另一个选择是使用
ExportFactory
,例如:Are you sure you are recomposing your consumer class? The
NonShared
creation policy will ensure that a new instance is created each time the part is required to compose, so I would check the other side of it, which is the class where you are[Import]
-ing your part. Is that class being recomposed correctly?Your other option is to use an
ExportFactory
, e.g.:您应该创建一个工厂并将其导出,然后将其用作您的财产。 MEF 部件创建策略适用于 MEF 构造具有依赖性的对象时,而不是访问这些依赖性时。
You should create a factory and export that instead and then use it as your property. MEF part creation policy applies to when MEF is constructing the object which has dependency not when those dependencies are accessed.