Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to initialize a model and view in WPF CAL MVVM

I have come accross two ways of initializing Views and ViewModels in WPF CAL MVVM.

1 - Seems to be more popular. Requires you to resolve the ViewModel to automatically resolve the View. The ViewModel contains information about the View.

    public interface IView
    {
        void SetModel(IViewModel model);
    }

    public interface IViewModel
    {
        IView View { get; }
    }

    public class View
    {
        public void SetModel(IViewModel model)
        {
            this.DataContext = model;
        }
    }

    public class ViewModel
    {
        private IView view;

        public ViewModel(IView view)
        {
            this.view = view;
        }

        public IView View { return this.view; }
    }

2 - Seems a lot cleaner and removes the View from the ViewModel. Requires you to resolve the View to automatically resolve the ViewModel. Injects objects into the view (Not sure if this is good or not).

    public interface IView
    {
    }

    public interface IViewModel
    {
    }

    public class View
    {
        private IViewModel model;

        public View(IUnityContainer unityContainer)
        {
            this.model = unityContainer.Resolve<IViewModel>();
            this.DataContext = this.model;
        }
    }

    public class ViewModel
    {
    }

What is the accepted method of initializing the views and models and what are the advantages and disadvantages of each method. Should you be injecting objects into your view?

like image 913
anon Avatar asked Jan 15 '10 15:01

anon


1 Answers

They are both valid, but #1 tends to be more testable (it at least makes your tests more concise). The advantage to #2 is that it tends to be more explicit and makes maintenance a little more clear, especially when you have a lot of turnover, that kind of thing. Takes less explaining (though this is not a reason to adopt it, it's just a truism).

The difference is that #1 is called Dependency Injection and #2 is called Service Location. They are often confused because they both generally utilize some sort of IoC container (although this doesn't have to be the case).

It's a matter of preference in the end, but as I said I think you will find #1 a lot easier to test... you won't have to involve the IUnityContainer interface in your testing / mocking.

like image 116
Anderson Imes Avatar answered Nov 09 '22 04:11

Anderson Imes