Skip to content
This repository has been archived by the owner on Sep 23, 2021. It is now read-only.
Gennady Verdel edited this page Aug 9, 2016 · 1 revision

The purpose of this package is to provide an implementation for View Model Factory pattern using an Inversion-Of-Control container.

The pattern itself is used whenever there's run-time data that needs to be injected into the dynamically created view model. Run-time data cannot be registered into the container inside the app's composition root and thus has to be injected dynamically. On the other hand, there are other dependencies for the requested view model that can be injected by the container. The view model factory pattern provides a recipe for such scenario. Consider the case where there's a data service that exposes a collection of warehouse items. This collection may change regardless of the Presentation actions and thus implements the INotifyCollectionChanged to notify the potential observers about the changes. On the other hand the collection of the models is displayed using so-called object view models which can be thought of as wrappers around the models (they can contain commands, computed properties, etc.) The models are created dynamically and so are the wrappers. View model factory provides a neat shortcut for abstracting the way the wrappers are created.

    [UsedImplicitly]
    public class WarehouseItemsViewModel : PropertyChangedBase
    {
        private readonly IDataService _dataService;
        private readonly IViewModelFactory _viewModelFactory;

        public WarehouseItemsViewModel(
            IDataService dataService,
            IViewModelFactory viewModelFactory)
        {
            _dataService = dataService;
            _viewModelFactory= viewModelFactory;
        }

        private ICollectionView _warehouseItems;
        public IEnumerable WarehouseItems
        {
            get { return _warehouseItems ?? (_warehouseItems = CreateWarehouseItems()); }
        }

        private ICollectionView CreateWarehouseItems()
        {
            var wc = new WrappingCollection
            {
                FactoryMethod =
                    o =>
                        _viewModelFactory.CreateModelWrapper<IWarehouseItem, WarehouseItemViewModel>(
                            (IWarehouseItem) o)
            }.WithSource(_dataService.WarehouseItems);

            return wc.AsView();
        }
    }
Clone this wiki locally