2

In an MVVM application I need to use some services that are persistent, e.g. network services like P2P and WCF where the main "engine" or server endpoint must remain up and running during the lifetime of my application. Currently I have coded these into singletons that abstracts functionality, using the engine or server instance internally.

Another example is a central message queue (like a main loop/BlockingCollection) where I need to queue various tasks that need to be processed sequentially.

How should I define and access such services in an MVVM context? I have read about the service locator pattern but this and singletons are often described as an anti-patterns?

  • 2
    In the Model. MVVM is a UI pattern; everything that doesn't have to do with UI goes in the Model. – Robert Harvey Apr 26 '15 at 0:19
  • But: if multiple models need to talk to a single P2P server instance how is the P2P server made available and accessed? Surely not in a model? Also if I have a main loop processing a queue of tasks - how is this main loop defined and accessed so other components (e.g. P2P server, WCF server, monitoring component) can add tasks to it? Another model? To me I need a service layer (P2P, WCF, monitoring, etc.) but it appears service locators and singletons are not well-regarded. So what is? – DaveO Apr 26 '15 at 3:50
  • A service layer would be considered part of the Model of MVVM. The Model part is not a monolithic thing and usually other design patterns are used there. The common alternative for service locators and singletons is Dependency Injection. – Bart van Ingen Schenau Apr 26 '15 at 9:21
2

My tip is to look into Dependency injection. Here is a real world example of what you wanna do

Inject your behavior into the VM

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.GUI/Shells/Curves/CurveSettingsViewModel.cs#L18

In this example I inject a ISettingsManager into the VM

public CurveSettingsViewModel(ISettingsManager settingsManager)
{
     this.settingsManager = settingsManager;
}

And it happens to be configured as a singleton by the IoC (Nothing the VM is aware of though and should not care about)

https://github.com/AndersMalmgren/FreePIE/blob/master/FreePIE.Core/Services/ServiceBootstrapper.cs#L49

private static void BindPersistance(StandardKernel kernel)
{
    kernel.Bind<ISettingsManager>().To<SettingsManager>().InSingletonScope();
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.