Func<XViewModel> delegates in VM constructors? (HelloScreens example)

Nov 25, 2010 at 1:28 AM

I'm trying to get my head wrapped around the HelloScreens example and I'm a little stuck on the constructors for the workspace view models. Their importing constructors take parameters like Func<OrderViewModel> orderVMFactory instead of having their VM dependencies injected directly by MEF. Can someone please explain to me two things:

1. Why is it done this way?

2. Where are these Funcs being exported so that MEF can find them?

Sorry if this question is a little basic, but it has my confused. Thanks.

Coordinator
Nov 25, 2010 at 2:10 AM

The funcs are explicitly registered with MEF's container. Have a look at the bootstrapper code to see this. The instance cannot be injected because we don't want a singleton, but need to be able to create new instances of the class on the fly. There may be a more MEF oriented way of doing this, but I couldn't remember it, so I justed used a mechanism that would work with every container.

Nov 25, 2010 at 2:28 AM

Ok that clears that up, thanks a lot. For reference, you can force MEF to generate new instances, rather than using singletons, by applying 

[PartCreationPolicy (CreationPolicy.NonShared)]

Coordinator
Nov 25, 2010 at 1:57 PM

The CustomerViewModel is marked with that attribute, but we cannot inject one into the workspace because that will give us only one instance for the workspace.  Rather, the CustomersWorkspaceViewModel needs a way to create the instances of CustomerViewModel, one for every record you open. For that, we need some sort of factory.