The first API endpoint I need is the list of all the groups. This means retrieving the countries from the database and transform them in the groups. To accomplice this I’ll be using the Repository-Service pattern.

Repository-Service pattern

Repository-Service pattern breaks up the business layer of the application into two distinct parts. The repository retrieves the data, in my case, from the SQLite database. That’s all it does. Handle the database communication.

On top of the repository is the service. The service is where the real business logic can be added. If there is a need, the service will transform the data it gets from the repository into the data the controller needs.


The service can very well be just a simple pass-through when the data from the database is just what you need. But in case of the groups, the database only contains a list of countries. That data needs to be transformed into a list of groups. This is the task that the service needs to do.

public class GroupsService: IGroupsService
	public async Task<List<Group>> GetGroupsAsync()
		var list = new List<Group>();
		Group group = null;
		string lastGroup = "";

		foreach (var country in _countriesRepository.GetCountriesAsync())
			if (country.GroupID != lastGroup)
				group = new Group
					GroupID = country.GroupID,
					Countries = new List<Country>()
			lastGroup = country.GroupID;

		return list;

First the countries are retrieved from the database by the repository. When that data is available, the service goes through the countries, create the group and add the countries to it. When the next country is part of another groups, a new group is added to the list and continues using that group.

Units tests

I also created a small simple (read: too simple) unit test to test that service.

First I needed to mock the repository. For now it just returns a couple of countries, four in this case, split in two groups. In a later stage I probably need to extend this. There are specialist mocking library for .NET. Moq seems to be the popular choice, but that is for another day.

The data from the mocked repository is processed by the service, the real purpose of the test.

At this moment the assert is too simple. It only checks if there are two groups in the list. More checks are needed, but for now it will do.