Creating the View and View Model Using Unity
Using Unity as your dependency injection container is similar to using MEF, and both property-based and
In your example, the viewmodel is of type QuestionnaireViewModel
, which is a concrete class. Since it's a concrete class, when you resolve the view using container.Resolve<QuestionnaireView>()
, unity will instantiate the viewmodel for you by calling container.Resolve<QuestionnaireViewModel>()
behind the scenes.
In this case, registering your viewmodel is redundant. However, when using dependency injection you usually want to work with interfaces rather than classes, so your constructor would look like this:
public QuestionnaireView(IQuestionnaireViewModel viewModel)
{
this.DataContext = viewModel;
}
Now that your constructor receives an interface rather than a class as a parameter, Unity doesn't know which implementation of the interface you'd like to use. To tell Unity that, you need to register your viewmodel to the container:
container.RegisterType<IQuestionnaireViewModel, QuestionnaireViewModel>();
so now when you resolve your view, Unity will look up which class it should use as an implementation of IQuestionnaireViewModel
, see that it's QuestionnaireViewModel
and use it.
Unity is being used, since in order for the constructor to get its parameters, you need to resolve the view using the container. Unity is not used if you instantiate the view yourself using new QuestionnaireView()
, i.e. no constructor or property injection will occur.
I think it's mostly a matter of what's more comfortable and where you need to use the injected members. A lot of times you just want to set a local variable in the constructor and not create a property just for performing the injection.
One good thing about property-injection though is the fact that you can use the container.BuildUp()
method for instances that were created by using new
rather than container.Resolve<>()
. This way, you can inject members into properties even after creation - which is something you can't do with constructor injection.