title: MVVM view model and async data initialisation
body: <p>I have a view model with a constructor that requires a service. I'm using GalaSoft's MvvmLight which uses a service locator to wire up the view to the view model.</p>
  
  <p>SimpleIOC handles providing the service to the viewmodels constructor fine, but I somehow need to populate my viewmodel with data from a data source . My Viewmodel looks a like this:-</p>
  
  <pre><code>    public class MainPageViewModel : ViewModelBase
  {
      private readonly GroupService _groupService;
      private readonly GroupFactory _groupFactory;
      private readonly ObservableCollection&lt;GroupVM&gt; _groupVms = new ObservableCollection&lt;GroupVM&gt;();
  
  
      public MainPageViewModel(Domain.Services.GroupService groupService, VMFactories.GroupFactory groupFactory)
      {
          _groupService = groupService;
          _groupFactory = groupFactory;
      }
  
      public async Task Init()
      {
          var groups = await _groupService.LoadGroups();
          foreach (var group in groups)
          {
              GroupVms.Add(_groupFactory.Create(group));
          }
      }
  
      public ObservableCollection&lt;GroupVM&gt; GroupVms { get { return _groupVms; } }
  }
  </code></pre>
  
  <p>Somehow the init method needs to be called an awaited, but I don't know how best to do this? I can think of three options:-</p>
  
  <ol>
  <li>I just call Init on the constructor, but not await it (I know thats really bad practice)</li>
  <li>I call Init on ViewModelLocator object, but since I can't return a task I again can't await the init</li>
  <li>On the view's load I cast the DataContext to some sort of IAsyncViewmodel and await the init method.</li>
  </ol>
  
  <p>I have used option 3 in a previous windows 8 store project but it just feels wrong. Any advice would be really appreciated!</p>
  
  <p>Thanks</p>
  
  <p>Ross</p>