What exactly are “WPF services”?

Martin Fowler has a description of what a service is in his Dependency Injection article. Put simply, a service is an object that provides functionality to be used by other objects. You’ll find the term used heavily when discussing the patterns Inversion of Control and Service Locator.

To make this concrete with the topic at hand, let’s think about how we’d display a message box in the MVVM pattern. Calling MessageBox.Show() would be bad, Ray. This ties the ViewModel tightly to the UI architecture, and makes the ViewModel difficult to test. Instead, one solution would be to use a service, which we’ll call IDisplayMessage. This service is supplied to the ViewModel somehow (through one of the two patterns above), and this service is used to “display” a message. During normal operation, a concrete version of this service will call MessageBox.Show(), but during testing we can provide a different concrete version (a test double) that behaves differently (a noop often, or if we’re ensuring the ViewModel displays the message, a version that records the call so we can assert that it occurred). Onyx (disclaimer: I’m the author) provides just such a service, and the infrastructure necessary for providing this service (and others) to your ViewModel.

Update: Since this response was made, I’ve written a blog post Services: Your ViewModel Deathstar, which covers the topic fairly well. This was part of a “series” of posts, and readers may also be interested in the first post Behavior – Your Trusty ViewModel Bazooka.

Leave a Comment