0

我需要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
}

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

4

1 回答 1

0

您是否正在检查构造函数中的值?直接在属性上装饰的导入在构造函数之后解析。如果你想访问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  
    }
}
于 2014-07-29T09:30:40.243 回答