我正在學習與MVVM一起使用EF4.1,並且在這些教程之一中他們使用調用另一個視圖模型(EmployeeListViewModel)時使用的Repository對象創建MainWindowViewModel。下面是代碼:何處定義存儲庫?
public MainWindowViewModel()
{
IObjectContextAdapter adapter = ((IObjectContextAdapter)new SidekickEntities());
_vmRepository = new GenericRepository(adapter.ObjectContext);
EmployeeListViewModel viewModel = new EmployeeListViewModel(_vmRepository);
this.ViewModels.Add(viewModel);
}
public EmployeeListViewModel(GenericRepository repository)
{
if (repository == null)
{
throw new ArgumentNullException("repository");
}
_employeeRepository = repository;
this.AllEmployees = new ObservableCollection<Employee>(_employeeRepository.GetAll<Employee>());
}
我想知道的是,爲什麼在庫中創建MainWindowViewModel,然後傳遞到EmployeeListViewModel?爲什麼不只是創造EmployeeListViewModel存儲庫這樣的:
public MainWindowViewModel()
{
EmployeeListViewModel viewModel = new EmployeeListViewModel();
this.ViewModels.Add(viewModel);
}
public EmployeeListViewModel()
{
IObjectContextAdapter adapter = ((IObjectContextAdapter)new SidekickEntities());
_employeeRepository = new GenericRepository(adapter.ObjectContext);
this.AllEmployees = new ObservableCollection<Employee>(_employeeRepository.GetAll<Employee>());
}
我非常新的EF但似乎乾淨了一點,在每組單獨的視圖模型庫。當ViewModel問題不再被使用,而是直到MainWindowViewModel關閉時纔會清理存儲庫,否則會創建太多的存儲庫實例?
好的謝謝。很高興知道,在我進入開發階段之前, :) – BrianKE