简体   繁体   中英

How to retrieve/import object using MEF in Prism

I have a requirement to have one object ( RuleFile ), representing file to be serialized, across the whole application like word (*.docs) file that will be associated with my application.

I am using Prism 5 along with MEF as a dependency injection container.

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

Now i have decorated the object with [Export] and trying to import it in one of the MyViewModel but it is giving null .

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

Kindly direct me what am i missing? Or tell me any other way to best handle this scenario.

Are you checking the value in the constructor? Imports that are decorated directly on the property are resolved after the constructor. If you want to access the RuleFile in the constructor you'd need to set it up like this

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

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

Alternatively, you can implement the IPartImportsSatisfiedNotification which will give you a notification method to signify that the imports have been resolved. Like this

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM