Loading Data Using Services with BuildIt.Lifecycle

The BuildIt.Lifecycle automatically creates instances of ViewModels and associates them with the corresponding page/view as the user steps between application states. Behind the scenes this uses Autofac to create these instances and ensure any dependencies are resolved. ViewModels that require access to device hardware, or to services that load or save data, can simply include the interface in the constructor. Take the following example where the MainViewModel relies on an instance of the IDataService interface to populate the Contacts collection.

public interface IDataService
{
    Task<IEnumerable<string>> LoadContacts();
}

public class MainViewModel : BaseViewModelWithCompletion<MainCompletion>
{
    public ObservableCollection<string> Contacts { get; }=new ObservableCollection<string>();
    private IDataService Data { get; }
    public MainViewModel(IDataService data)
    {
        Data = data;
    }
    public async Task LoadData()
    {
        var contactList = await Data.LoadContacts();
        contactList.DoForEach(Contacts.Add);
    }

We need to make two changes to our application declaration. The first is to register the implementation of IDataService, which we’ll do in App.xaml.cs

var core = new SimpleStatesApplication();
var wm = new WindowManager(core);
await core.Startup(builder =>
{
    builder.RegisterType<UWPDataService>().As<IDataService>();
});

public class UWPDataService : IDataService
{
    public async Task<IEnumerable<string>>  LoadContacts()
    {
        return new []{“Joe”, “Bob”, “Frank”};
    }
}

The other change is to then invoke this method when the MainViewModel is used, this is when the Home state is changed to. We add the following to our state declarations

(group.Item2.States[AppStates.Home] as IViewModelStateDefinition<AppStates, MainViewModel>)
    .WhenChangedTo(async vm => await vm.LoadData());

Note that we can also register services as part of our application class, allowing them to be registered within the PCL, rather than the platform specific libraries. This is useful for services that you want to use the same implementation for all supported platforms.

public class SimpleStatesApplication : RegionAwareBaseApplication<PrimaryRegion>
{
    protected override void RegisterDependencies(ContainerBuilder builder)
    {
        base.RegisterDependencies(builder);
        builder.RegisterType<BasicDebugLogger>().As<ILogService>();
    }
}

The ILogService is used within BuildIt.Lifecycle, so registering this implementatino will allow you to view the diagnostic information in the Output window within Visual Studio.

Leave a comment