I need some help to understand how to instantiate ViewModels without having all of them as parameters in the MainViewModel Class constructor.
Could any of you help me to get my head around and get rid of so many parameters in the constructor. I've read about FactoryPatterns but I don't understand how to implement it or maybe that is not the solution?. Anyway here's the code.
Thank you. Pls help me this is driving me nuts!
app.xaml.cs
private readonly ServiceProvider _serviceProvider;
public App()
{
ServiceCollection services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
}
private void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<MainWindow>();
// Services
services.AddSingleton<ICustomerService, CustomerService>();
// ViewModels
services.AddScoped<MainViewModel>();
services.AddScoped<CustomerViewModel>();
services.AddScoped<CustomerAddViewModel>();
services.AddScoped<CustomerEditViewModel>();
services.AddScoped<ServiceViewModel>();
}
private void OnStartup(object sender, StartupEventArgs e)
{
var mainWindow = _serviceProvider.GetService<MainWindow>();
mainWindow.DataContext = _serviceProvider.GetService<MainViewModel>();
mainWindow.Show();
}
MainViewMode.cs
public class MainViewModel : ViewModelBase
{
private CustomerViewModel _customerViewModel;
private CustomerAddViewModel _customerAddViewModel;
private CustomerEditViewModel _customerEditViewModel;
private ViewModelBase _selectedViewModel;
public ViewModelBase SelectedViewModel
{
get => _selectedViewModel;
set
{
_selectedViewModel = value;
NotifyPropertyChanged();
}
}
public RelayCommand CustCommand { get; set; }
public RelayCommand ServCommand { get; set; }
**public MainViewModel(
CustomerViewModel customerViewModel,
CustomerAddViewModel customerAddViewModel,
CustomerEditViewModel customerEditViewModel)
{
_customerViewModel = customerViewModel;
_customerAddViewModel = customerAddViewModel;
_customerEditViewModel = customerEditViewModel;
CustCommand = new RelayCommand(OpenCustomer);
}**
private void OpenCustomer()
{
SelectedViewModel = _customerViewModel;
}
}
CustomerViewModel
public class CustomerViewModel : ViewModelBase
{
private ICustomerService _repo;
private ObservableCollection<Customer> _customers;
public ObservableCollection<Customer> Customers
{
get => _customers;
set
{
_customers = value;
NotifyPropertyChanged();
}
}
public CustomerViewModel(ICustomerService repo)
{
_repo = repo;
}
public async void LoadCustomers()
{
List<Customer> customers = await _repo.GetCustomers();
Customers = new ObservableCollection<Customer>(customers);
}
}