Repositories – Getting the Data to the ViewModel

Right now the ViewModel is pretty hideous. It shouldn’t be responsible for fetching the data, much less creating it – that’s a clear violation of the Single Responsibility Principle and all round Bad Idea (TM). So let’s make that the responsibility of a repository.

I have a go-to repository interface that I use as a starting point:

IEntity is there purely to make sure that the class in the repository has an Id field. Feel free to leave it out if you don’t need it, but it’s useful if you want to have a unique identifier for retrieving/updating entities in your repository.

For use with SQLite, I use IEntity to create a primary key on the Id:

…and then I make my ToDoItem class inherit from it.

Now my ToDoItem class fulfils all the requirements for use in a repository that implements IRepository<T>. Eventually I want that to be a repository that uses SQLite, but for now I’m going to use a bare-bones mock-up with some hard-coded data.

I’ll use this later in unit testing, so creating it is not actually a waste of time.

and now, finally, I can change my ViewModel to use this repository:

Now, looking at this, the ViewModel is still in a world of wrong. In fact, it’s so wrong that almost every line in it needs to be changed. We have tight coupling, we are blocking the UI thread because you can’t use ‘await’ in a constructor, we’re using a mock repository and an unsuitable collection, but fear not – all this will be addressed over the course of the next few posts…

Leave a Reply

Your email address will not be published. Required fields are marked *