Search code examples
c#dependency-injectionservicemefprism-4

PRISM + MEF -- Importing a Service


I'm trying to figure out how to import a service into my ViewModel properly... here's my relevant code (I've omitted the unimportant stuff):

ClientBootstrapper.cs:

public sealed class ClientBootstrapper : MefBootstrapper
{
    protected override void ConfigureAggregateCatalog()
    {
        base.ConfigureAggregateCatalog();

        //Add the executing assembly to the catalog.
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
    }

    protected override DependencyObject CreateShell()
    {
        return Container.GetExportedValue<ClientShell>();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();

        Application.Current.MainWindow = (Window)Shell;
        Application.Current.MainWindow.Show();
    }
}

ClientShell.xaml.cs:

[Export()]
public partial class ClientShell : Window
{
    [Import()]
    public ClientViewModel ViewModel
    {
        get
        {
            return DataContext as ClientViewModel;
        }
        private set
        {
            DataContext = value;
        }
    }

    public ClientShell()
    {
        InitializeComponent();
    }
}

ClientViewModel.cs:

[Export()]
public class ClientViewModel : NotificationObject, IPartImportsSatisfiedNotification
{
    [Import()]
    private static RandomService Random { get; set; }

    public Int32 RandomNumber
    {
        get { return Random.Next(); } //(2) Then this throws a Null Exception!
    }

    public void OnImportsSatisfied()
    {
        Console.WriteLine("{0}: IMPORTS SATISFIED", this.ToString()); //(1)This shows up
    }
}

RandomService.cs:

[Export()]
public sealed class RandomService
{
    private static Random _random = new Random(DateTime.Now.Millisecond);

    public Int32 Next()
    {
        return _random.Next(0, 1000);
    }
}


I do get the notification that all the import parts have been satisfied (1), but then I get a NullReferenceException (2) on return Random.Next(); inside of the ClientViewModel. Not sure why I would get a NullReferenceException after I'm told that all Imports are satisfied...


Solution

  • MEF won't satisfy imports on a static property. Make the random service an instance property.