kbeal2k
kbeal2k

Reputation: 672

Shared data service between views in MVVM - global or constructor injection?

If I have a data/web service that multiple view models need access to what is the preferred "MVVM way"?

Do I have a global static service or do I pass in an instance of my service to all my view models? I personally can't see an advantage of one approach over the other.

Upvotes: 0

Views: 791

Answers (2)

TheZenker
TheZenker

Reputation: 1740

In addition to using Dependency Injection also consider a ServiceLocater approach, where each ViewModel would, if not passed an instance of a service, would call to the ServiceLocator to obtain an instance of the registered service at run time.

Fowler on DI and ServiceLocator

MSDN on ServiceLocator

Upvotes: 0

Ray Booysen
Ray Booysen

Reputation: 30031

Passing in an interfaced version of your service allows your class to be easily unit tested. With global static state, this is not as clean or as easy.

Making the class take an interface also defines the contract for your class. You're essentially saying, "ClassA requires IServiceA and IServiceB to function correctly". With global static state, there is no such contract.

Upvotes: 2

Related Questions