Can I use UnityContainer in View’s codebehind when I want to write good MVVM program?
this.DataContext = uc.Resolve<MainViewModel>();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
ServiceLocator is an anti-pattern, you shouldn’t be using it. The reason it’s an anti-pattern is because it allows for objects to be resolved inside a class at any time, reducing the usefulness of your DI and making your code harder to unit test.
My suggestion would be to do one of the following:
a) Inject the viewmodel into the view through it’s constructor. Resolve the view using Unity so that it resolves all the views dependencies (the view model) for you.
So:
public partial class View:UserControl,IViewFoo
{
public View(IViewModel viewModel)
{
DataContext=viewModel;
}
var view=_container.Resolve();
}
b)
Use an attached property to inject the viewmodel into the DataContext for you. MEFEDMVVM and MVVMLite both do this (look them up on Codeplex)
c)
Follow a convention-based approach where the viewmodel gets assigned to the view based on them having compatible names (MainView.cs and MainViewModel.cs). Caliburn Micro does this and is very nice to use. This can also be found on CodePlex.