MEF:如何检索类型的新实例?

发布于 2024-11-28 05:15:07 字数 368 浏览 0 评论 0原文

在我的类中,我有一个类导入如下类型:

[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨后彩虹 2024-12-05 05:15:07

您确定要重构您的消费者阶层吗? NonShared 创建策略将确保每次需要组合该部分时都会创建一个新实例,因此我会检查它的另一面,即您所在的类[Import ]-你的部分。该类是否被正确重构?

您的另一个选择是使用 ExportFactory,例如:

[Import] public ExportFactory<ContactViewModel> ViewModelFactory { get; set; }

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

[Import] public ExportFactory<ContactViewModel> ViewModelFactory { get; set; }
私野 2024-12-05 05:15:07

您应该创建一个工厂并将其导出,然后将其用作您的财产。 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文