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?
-
2In the Model. MVVM is a UI pattern; everything that doesn't have to do with UI goes in the Model.Robert Harvey– Robert Harvey2015年04月26日 00:19:11 +00:00Commented Apr 26, 2015 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– DaveO2015年04月26日 03:50:44 +00:00Commented Apr 26, 2015 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– Bart van Ingen Schenau2015年04月26日 09:21:28 +00:00Commented Apr 26, 2015 at 9:21
1 Answer 1
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
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)
private static void BindPersistance(StandardKernel kernel)
{
kernel.Bind<ISettingsManager>().To<SettingsManager>().InSingletonScope();
}
Explore related questions
See similar questions with these tags.