Where to store application settings/state in a MVVM application

前端 未结 3 438
囚心锁ツ
囚心锁ツ 2021-01-30 11:18

I\'m experimenting with MVVM for the first time and really like the separation of responsibilities. Of course any design pattern only solves many problems - not all. So I\'m try

3条回答
  •  面向向阳花
    2021-01-30 12:05

    If you weren't using M-V-VM, the solution is simple: you put this data and functionality in your Application derived type. Application.Current then gives you access to it. The problem here, as you're aware, is that Application.Current causes problems when unit testing the ViewModel. That's what needs to be fixed. The first step is to decouple ourselves from a concrete Application instance. Do this by defining an interface and implementing it on your concrete Application type.

    public interface IApplication
    {
      Uri Address{ get; set; }
      void ConnectTo(Uri address);
    }
    
    public class App : Application, IApplication
    {
      // code removed for brevity
    }
    

    Now the next step is to eliminate the call to Application.Current within the ViewModel by using Inversion of Control or Service Locator.

    public class ConnectionViewModel : INotifyPropertyChanged
    {
      public ConnectionViewModel(IApplication application)
      {
        //...
      }
    
      //...
    }
    

    All of the "global" functionality is now provided through a mockable service interface, IApplication. You're still left with how to construct the ViewModel with the correct service instance, but it sounds like you're already handling that? If you're looking for a solution there, Onyx (disclaimer, I'm the author) can provide a solution there. Your Application would subscribe to the View.Created event and add itself as a service and the framework would deal with the rest.

提交回复
热议问题