1

I've added a call to an asynchronous method in my constructor, in order to initialize data for the ViewModel when loaded.

But I noticed there is a warning on the calling of that method in the VM constructor. It states that "this call is not awaited"

I understand from this error that the call needs to be prefixed with await. but this would also mean that the constructor would have to be marked as an async Task which I know it can't be in C#. As constructors can't be async.

I did come across a similar question here, but some practical code examples related to my implementation that uses dependency injection, would be a help.

Does anyone have an example, of how to refactor the call out of the constructor? Or what implementation pattern to use instead?

This is a summarized version of the ViewModel, showing how I call the method in the constructor:

namespace MongoDBApp.ViewModels
{

    [ImplementPropertyChanged]
    public class CustomerDetailsViewModel 
    {

        private IDataService<CustomerModel> _customerDataService;
        private IDataService<Country> _countryDataService;

        public CustomerDetailsViewModel(IDataService<CustomerModel> customerDataService, IDataService<Country> countryDataService) 
        {
            this._customerDataService = customerDataService;
            this._countryDataService = countryDataService;

            //warning about awaiting call, shown here...
            GetAllCustomersAsync();

        }


      #region Properties


        public ObservableCollection<CustomerModel> Customers { get; set; }

        public ObservableCollection<Country> 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

    }
}
Community
  • 1
  • 1
Brian Var
  • 6,029
  • 25
  • 114
  • 212
  • 1
    It sounds to me like you should move your async call into the properties themselves and lazy load them there. – Peter M Dec 15 '15 at 21:46
  • ok could you provide an example of how to implement that? – Brian Var Dec 15 '15 at 21:58
  • 1
    You want something like http://blog.stephencleary.com/2012/08/asynchronous-lazy-initialization.html – Peter M Dec 15 '15 at 22:06
  • 1
    I ended up using the "The Asynchronous Initialization Pattern" example from the below link. As the first factory example doesn't seem to work with my DI ctor. http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html – Brian Var Dec 15 '15 at 23:16

0 Answers0