thats the way josh smith is doing the add-a-customer-procedure:
**CustomerViewModel**.cs:
public void Save()
{
_customerRepository.AddCustomer(_customer);
}
**CustomerRepository**.cs:
public void AddCustomer(Customer customer)
{
//...
_customers.Add(customer);
if (this.CustomerAdded != null)
this.CustomerAdded(this, new CustomerAddedEventArgs(customer));
}
**AllCustomersViewModel**.cs(acts as Controller):
void OnCustomerAddedToRepository(object sender, CustomerAddedEventArgs e)
{
var viewModel = new CustomerViewModel(e.NewCustomer, _customerRepository);
this.AllCustomers.Add(viewModel);
}
strong textWouldn`t it be better to do this?:
**CustomerViewModel**.cs:
public void Save()
{
if (this.CustomerAdded != null)
this.CustomerAdded(this, new CustomerAddedEventArgs(customer));
}
AllCustomersViewModel.cs(acts as Controller):
void OnCustomer**ADDING**ToRepository(object sender, CustomerAddedEventArgs e)
{
_customerRepository.Add(e.NewCustomer);
var viewModel = new CustomerViewModel(e.NewCustomer);
this.AllCustomers.Add(viewModel);
}
This step in the CustomerViewModel.cs could also be in the Controller because the Controller holds 1/all refererence(s) to the Service/Repository of the Customer/Product/Order etc…
if (this.IsNewCustomer)
_customerRepository.AddCustomer(_customer);
When I have now still a Order/ProductViewModel working for the same controller I have 3 instances of the repository. If the repository would be in the controller`s Ctor instantiated I have only ONE instance.
With josh smith architecture you have a customerRepo in the Controller AND CustomerViewModel.
With my idea you have only ONE customerRepo in the controller AND the CustomerViewModel`s Save/Add method could be subscribed to the Controllers OnAddCustomer method.
Why did Josh smith took a
public event EventHandler<CustomerAddedEventArgs> CustomerAdded;
and not a
simple public Action<Customer> AddDocumentDelegate;
What do you think? Do you see any disadvantage in my idea?
Your idea is right. The viewModel should be a view specific representation of your model and it should not call your repositories. Your controller could listen on the events from view (button click, submit etc) and then call the repositories.
There are other posts on this topic you should check –
http://www.weask.us/entry/mvvm-put-data-access-layer
MVVM where to put Data Access Layer?