I also personally do not mind Dispatcher in the model class. I have not seen any serious problems with this, but it gives maximum flexibility to your code.
But I like the idea of ββusing Dispatcher as much as possible in your infrastructure code. Just as you did with the RaisePropertyChanged method (BTW, in the case of RaisePropertyChanged you do not need to send anything - the binding already does this for you, you only need to send changes to the collection).
The biggest and only drawback that I see here is unit testing. When you try to test your logic, it may be difficult to use Dispatcher . Imagine if you had code like this in your view model:
private void UpdateMyCollection() { IList<ModelData> dataItems = DataService.GetItems(); // Update data on UI Dispatcher.BeginInvoke(new Action(() => { foreach (ModelData dataItem in dataItems) { MyObservableCollection.Add(new DataItemViewModel(dataItem)); } })); }
This type of code is pretty typical when it comes to updating collections from a thread other than the UI. Now, how would you write a unit test that checks the logic of adding items to an observable collection? First of all, you need to make fun of the Dispatcher property, because Application.Current is null during the execution of the unit test. Secondly, how do you mock this? Will you create a special thread that will simulate a user interface thread and use the Dispatcher this thread? So these are the things.
The bottom line is that if you want your code to be module-friendly, you need to think about how you will mock Dispatcher . This is the only problem.
Update:
The second example you provided will work without Dispatcher (binding will do the trick).
Pavlo Glazkov
source share