HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

ViewModel constructor with many parameters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withconstructorviewmodelmanyparameters

Problem

I have some ViewModels that have a lot of parameters like this one:

public class ProductsMainViewModel : NotificationObject, IActiveAware, ...
{
    public ProductsMainViewModel(IProductRepository productRepository, IWarehouseRepository warehouseRepository, IUnitOfMeasureRepository unitOfMeasureRepository,
            IProductCategoryRepository productCategoryRepository, IProductPriceRepository productPriceRepository, IPriceLevelRepository priceLevelRepository,
            ICodingRepository codingRepository, ICategoryRepository categoryRepository, IDialogService dialogService, Logging.ILoggerFacade logger, IRegionManager regionManager,
            IJsonSerializer jsonSerializer, ICodeService codeService, IEventAggregator eventAggregator)
    {
        // ...
    }
}


(All repositories have the same instance of IUnitOfWork)
Instantiating this is done by IUnityContainer, But there are some dialogs that get called in this ViewModel:

var viewModel = new ProductViewModel(_warehouseRepository, _unitOfMeasureRepository,
                _productCategoryRepository, _priceLevelRepository, _productPriceRepository, _codingRepository, _dialogService, _codeService, _jsonSerializer);

            var result = _dialogService.ShowDialog("ProductWindow", viewModel);
            if (result == true)
            {
                 // ...
            }


that their repositories must have the same IUnitOfWork of the current ViewModel. So I decided to pass parameters manually. I found it a good idea to "not reference any IoC container" in my ViewModel in here.


The benefit of this approach is that the ViewModel doesn't have any
knowledge of the (Unity) container. Also, in terms of understanding
the application design the dependencies of the ViewModel are easy to
see since they are in the constructor.

Well, any ideas on how to reduce the number of parameters? Any particular design pattern?

Is it a good idea to create a 'IFooRepositoriesContext' and p

Solution

why don't you write an abstract factory containing all the references you need?
You can then implement a factory method for your ViewModel creating an instance based on some configuration parameters.
Your client code now doesn't need to know the constructor sintax but just the configuration needed for the right instance.

Context

StackExchange Code Review Q#15947, answer score: 4

Revisions (0)

No revisions yet.