How to use Dependency Injection for creating ViewModels in a Master-Detail view
I'm building a Silverlight app using Jounce for my MVVM. I have a CustomerListViewModel (plural) which has a collection of CustomerViewModel objects (single).
I'm using Ninject for dependency injection, because my ViewModels will be depending on other classes (i.e. repositories, services, etc.).
Using the dependency injection is fairly easy, but now I'm a little stuck. When the CustomerListViewModel loads, it will go to the database (it already has its repository through DI) and get the Customer objects. These should be passed on to a CustomerViewModel.
How would I go about constructing these CustomerViewModel objects? I've always read that the Service Locator pattern is an anti-pattern, so this feels wrong:
private void GetCustomerss()
{
var customers = _customerRepository.GetAll();
IList<CustomerViewModel> customerViewModels = new List<CustomerViewModel>();
foreach (var customer in customers)
{
var customerViewModel = ObjectFactory.GetInstance<CustomerViewModel>();
customerViewModel.Model = customer;
customerViewModel.Add(customerViewModel);
}
Customers = new ObservableCollection<CustomerViewModel>(customerViewModels);
}
How could I avoid this anti-pattern? Or is it really not that bad?
This also makes my unittesting a little harder, because I can inject a mock ICustomerRepository into the CustomerListViewModel (in the constructor), but the ObjectFactory.GetInstance<CustomerViewModel>()
will work as it should, and also resolve underlying dependencies of CustomerViewModel. This will then fail, because I haven't set up Ninject for these underlying d开发者_StackOverflow中文版ependencies.
Here I described how I dealt with such scenario: http://pglazkov.blogspot.com/2011/04/mvvm-with-mef-viewmodelfactory.html. It is about MEF, but the idea is the same.
Basically you can have a separate service called IViewModelFactory
, using which you will create child view models. For unit tests you will be able to mock that service.
精彩评论