One of the things I'm watching closely in Prism 4 is the development of the MVVM documentation, QuickStarts and Reference Implemenatation. I have used Prism 2 in the past, and really struggled with MVVM combined with Dependency Injection.
In particular, I wasn't able to figure out a strategy of how to create a ViewModel which wraps a particular model object and use constructor injection to resolve dependencies at the same time.
I've been looking at the MVVM QuickStarts and RI in Prism 4 Drop 6, and I haven't yet seen a resolution for this question. Could someone please help me with this?
I'll illustrate with the following example from the RI: The QuestionnaireViewModel creates a collection of QuestionViewModels that wraps each of the Question model objects. For this purpose each QuestionViewModel derived type has a constructor that takes
a Question model object as a parameter which is used to create the ViewModel.
My dilemma is this: If I now have some dependencies to add to the QuestionViewModel using constructor injection (I'm using Unity at the moment), I can't find a way to marry that with the above approach of passing in the model object in the constructor.
If I do something like this:
private readonly myDependency;
public NumericQuestionViewModel(NumericQuestion question, IMyDependency myDependency) : base(question)
this.myDependency = myDependency;
then if I try to resolve the child ViewModel with Unity, then Unity will invariably inject a new instance of the model object (NumericQuestion) into my ViewModel along with the other dependencies, even though I haven't registered the model object with the
Unity container. I can't find a way to both provide the model object to wrap in the ViewModel
and resolve dependencies when I have hierarchical ViewModels.
I've played around with various options - having multiple constructors, using property injection instead, just newing up the viewModel and passing in the dependencies from the parent to the child, etc. - but none of them feel right to me.
I would like to keep the dependency injection consistent between all my ViewModels and not be forced to use one method of resolving for the parent and another for the children.
I'm aware that Unity 2.0 allows you to provide instances for certain parameters when resolving, but I'm limited to Unity 1.2 at the moment.