【问题标题】:How to retrieve/import object using MEF in Prism如何在 Prism 中使用 MEF 检索/导入对象
【发布时间】:2014-07-29 17:30:40
【问题描述】:

我需要在整个应用程序中拥有一个对象 (RuleFile),表示要序列化的文件,例如与我的应用程序关联的 word (*.docs) 文件。

我使用 Prism 5 和 MEF 作为依赖注入容器。

[Export]
[Serializable()]
public class RuleFile : NotificationBase, IRuleFile { }

现在我用[Export] 装饰了对象,并尝试将其导入MyViewModel 之一,但它给出了null

public class MyViewModel : ViewModelBase
{
    [Import]
    private RuleFile RuleFile; // 'null' coming here
}

请指导我我错过了什么?或者告诉我任何其他方式来最好地处理这种情况。

【问题讨论】:

  • 你有什么错误吗?是因为你的会员是私人的吗?在 mef.codeplex.com/wikipage?title=Declaring%20Imports 上,它说“注意:请注意,在完全信任的支持下导入或导出私有成员(字段、属性和方法)可能会在中等/部分信任下出现问题。”
  • 不会出现错误。正如你提到的,即使我将我的私人成员更改为公共财产,但仍然没有运气。
  • 抱歉,我不太了解 Prism。您是在配置 MEF 组合(容器和目录)还是应该由 Prism 来处理它?

标签: c# dependency-injection prism mef prism-5


【解决方案1】:

你在检查构造函数中的值吗?直接在属性上装饰的导入在构造函数之后解析。如果你想在构造函数中访问RuleFile,你需要像这样设置它

public class MyViewModel : ViewModelBase
{
    public RuleFile RuleFile { get; set; }

    [ImportingConstructor]
    public MyViewModel(RuleFile ruleFile)
    {
        RuleFile = ruleFile;
    }
}

或者,您可以实现IPartImportsSatisfiedNotification,它会给您一个通知方法来表示导入已解决。像这样

public class MyViewModel : ViewModelBase, IPartImportsSatisfiedNotification
{
    [Import]
    public RuleFile RuleFile { get; set; }

    public void OnImportsSatisfied()
    {
        // Signifies that Imports have been resolved  
    }
}

【讨论】:

  • 我自己想出了相同的解决方法,但这并没有回答我的问题,因为我在调用构造函数后尝试使用 RuleFile 对象。所以它不应该返回null。但是,我将您的答案标记为已接受,直到我得到真正的原因。
  • 在那种情况下,我唯一能想到的另一件事是您确定使用 MEF 来制作 MyViewModel 吗?我在那里看不到 [Export],但我不知道您是否错过了该示例。创建 MyViewModel 的代码在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多