MEF loading multiple instances of my MVVM Modules

Feb 13, 2013 at 5:18 PM
Edited Feb 14, 2013 at 4:54 PM
I'm new to MEF, and MVVM, and I'm having some problems.

I've finally got my View and ViewModel binding in my app; I'll explain what I've got and then the problem, hoping someone could help figure out what my problem is.

I have a host app - MVVM, the main view loads plugins from a dir and displays their name across the top. It also loads some items and displays them down the side.
public class Item
public Item()
public int Number { get; set; }
public string Name { get; set; }
To correctly load my modules, I was required to expose a public property of ResourceDictionary in the code behind of the view. I also expose the class of the viewmodel.

In my main app constructor I get all the resource dictionary types and add them to the app.current.resourcedictionary

then I get all my plugins and do a
foreach( var plugin in _plugins)
_plugins is an IEnumerable<Lazy<PlugingViewBase, IPluginMetaData>>;
In the constructor of each plugin I generate a GUID and console.writeline the new GUID.

when I call the .value of I get an init in the output, when the resourcedictionary is called I get an init as well...

What I want, is when changing the Item on the left, to update a textblock in the view of the plugin, this does not happen. However I have a button on the plugin view which does correctly update the TextBlock.

I think although all my classes have a creationpolicy shared - it still seems to create more than one instance.

Thanks for reading all that, All this MEF / MVVM is heavy going, so I'd be very glad of any assistance!
Feb 14, 2013 at 5:14 AM
Hi- which MEF version are you using, where are you creating the container, and how do you request the exports/satisfy the imports of the parts involved?

Feb 14, 2013 at 4:53 PM
Edited Feb 14, 2013 at 5:43 PM
Hi Nick,

I'm using the version that comes with .Net 4.5, but I solved my problem this morning!

The problem was that in my View the Xaml I was assigning the DataContext - so when my view model was loaded, it loaded the View which then loaded another instance of the ViewModel to attach to the view! consequentially I ended up with two ViewModels which was causing my problems with the INotifyPropertyChanged events.

The solution was to remove the DataContext from the xaml and in the code behind have
public myViewModel context
this.DataContext = value;
and that worked!!

I've also added some metadata like "name" so that I can display the plugins in a list without loading them from the lazy list, which means that it only gets loaded when going into the plugin.