Sharing/passing data via MEF?

Jun 21, 2011 at 3:10 AM

I was wondering if people do this.  I have some data that is used throughout my application.  I create a SharedData class that contains the data that is needed in different ViewModels and then use MEF with CreationPolicy.Shared so I have access to it.  Is this a bad practice?  Obviously there are other ways to accomplish this but it seems like a no-brainer.

Jun 21, 2011 at 1:03 PM

It's a fine practice. I've done that for many years. Just be aware that anything that is "shared" will remain in memory from the point it is first requested until the application is terminated.

Jun 21, 2011 at 2:32 PM

Do you ever bind directly to anything in "shared" data?

Jun 21, 2011 at 2:37 PM


Jun 21, 2011 at 2:58 PM

Good info, thanks.

Jun 21, 2011 at 4:34 PM

Would this be the equivalent of having a "global variable" object?

Jun 21, 2011 at 10:16 PM

Sort of. But the dependency is clearly stated in the constructor, where the instance of the shared instance is injected by the container.
Also, the class which uses the data is unaware that the instance is shared: only the container knows that just one instance of the SharedData is injected in multiple clients.
That allows you to unit test the VM without dealing with static global variables.

That being said, misusing the technique could certainly lead to *some* of the hassles of static variables.
_Generally speaking_ I would avoid, for example, to write code relying on the knowledge that some other piece of code around would put data into the shared structure at a certain point in time.
Edge cases aside, even using the shared data as a mean to propagate a global state on different pieces of the UI through binding has worked well for me. 

Jun 25, 2011 at 5:23 PM

Yeah, that's what I try and use it for.  I have a screen that has a map.  Stuff is plotted on the map, the user can mouse over things and a popup window displays some data.  Instead of passing data in the ctor of the windows vm, I inject that shared data the map screen has already populated.  I think this is an ok use.  This data could be passed in the ctor as well.