title: How to handle asynchronous method call in constructor?
body: <p>I've added a call to an asynchronous method in my constructor, in order to initialize data for the ViewModel when loaded.</p>
  
  <p>But I noticed there is a warning on the calling of that method in the VM constructor. It states that <code>"this call is not awaited"</code></p>
  
  <p>I understand from this error that the call needs to be prefixed with <code>await</code>. but this would also mean that the constructor would have to be marked as an <code>async Task</code> which I know it can't be in C#. As constructors can't be async.</p>
  
  <p>I did come across a <a href="https://stackoverflow.com/questions/23048285/how-to-call-async-method-in-constructor">similar question</a> here, but some practical code examples related to my implementation that uses dependency injection, would be a help.</p>
  
  <p>Does anyone have an example, of how to refactor the call out of the constructor?
  Or what implementation pattern to use instead?</p>
  
  <p>This is a summarized version of the ViewModel, showing how I call the method in the constructor:</p>
  
  <pre><code>namespace MongoDBApp.ViewModels
  {
  
      [ImplementPropertyChanged]
      public class CustomerDetailsViewModel 
      {
  
          private IDataService&lt;CustomerModel&gt; _customerDataService;
          private IDataService&lt;Country&gt; _countryDataService;
  
          public CustomerDetailsViewModel(IDataService&lt;CustomerModel&gt; customerDataService, IDataService&lt;Country&gt; countryDataService) 
          {
              this._customerDataService = customerDataService;
              this._countryDataService = countryDataService;
  
              //warning about awaiting call, shown here...
              GetAllCustomersAsync();
  
          }
  
  
        #region Properties
  
  
          public ObservableCollection&lt;CustomerModel&gt; Customers { get; set; }
  
          public ObservableCollection&lt;Country&gt; Countries { get; set; }
  
  
        #endregion
  
  
          #region methods
  
  
          private async Task GetAllCustomersAsync()
          {
              var customerResult = await _customerDataService.GetAllAsync();
              Customers = customerResult.ToObservableCollection();
  
              var countryResult = await _countryDataService.GetAllAsync();
              Countries = countryResult.ToObservableCollection();
          }
  
  
  
          #endregion
  
      }
  }
  </code></pre>